As in how does weakhashmap understand that a reference to one of its key is obsolete now especially if the key is a String which is pooled?
Asked
Active
Viewed 1,231 times
7
-
3This will help http://stackoverflow.com/questions/154724/when-would-you-use-a-weakhashmap-or-a-weakreference – jmj Nov 16 '10 at 16:35
2 Answers
3
You must not use String literals with WeakHashMap (well you can but there would be no point in it):
String myKey = "somekey";
instead you must use:
String myKey = new String("somekey");
In the latter case String is not pooled.

Peter Knego
- 79,991
- 11
- 123
- 154
-
Those examples are the same. A String literal is a String. At some stage after any String has no (strong/normal) references to it, it will be garbage collected. – Andrew G Jun 16 '15 at 12:44
-
Not quite the same: http://stackoverflow.com/questions/10578984/what-is-string-interning – Peter Knego Jun 22 '15 at 14:14
1
The word 'obsolete' is imprecise. The condition in question is 'garbage-collected'. A value is removed from the WeakHashMap when and if the key is garbage-collected. Period.

user207421
- 305,947
- 44
- 307
- 483