Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does weakhashmap work? [duplicate]

Tags:

java

hashmap

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?

like image 534
sandeepkunkunuru Avatar asked Nov 16 '10 16:11

sandeepkunkunuru


People also ask

How do WeakHashMap works?

Simply put, the WeakHashMap is a hashtable-based implementation of the Map interface, with keys that are of a WeakReference type. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use, meaning that there is no single Reference that point to that key.

What is true about a WeakHashMap garbage collector will automatically?

An entry in a WeakHashMap will be automatically removed by garbage collector when its key is no longer in ordinary use. Mapping for a given key will not prevent the key from being discarded by the garbage collector, (i.e. made finalizable, finalized, and then reclaimed).

Is WeakHashMap synchronized?

Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.

What is true about the WeakHashMap?

WeakHashMap is almost the same as HashMap except in the case of WeakHashMap if the object is specified as the key doesn't contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.


1 Answers

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.

like image 129
Peter Knego Avatar answered Oct 20 '22 15:10

Peter Knego