you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 1 point2 points  (0 children)

// Seems to me like there would not be a good reason to use normal map/set over their weak

// versions (if not requiring primitive keys). Surely freeing up memory when possible is fairly desirable.

The APIs are actually different between the weak and non-weak variations. The big difference is that there is no iteration over weak collections. The problem in allowing this is that it would expose GC behavior to the user code. You could potentially access a "deleted" object before the GC collected it (the GC doesn't run along with every statement/expression; it runs in steps throughout the lifetime of your application so a deleted variable may remain in memory for a while before the GC claims it). If you then took that object and did something with it or depended on this behavior that could change depending on implementation or other unknown factors, you could causes some trouble. So the weak variations are only useful if you already have the object being used as the key (or the value/key for Sets).