...
Code Block | ||
---|---|---|
| ||
// ... private Map<SSLSocket, InetAddress> m = Collections.synchronizedMap( new WeakHashMap<SSLSocket, InetAddress>() ); // ... |
Strong references prevent the garbage collector from reclaiming objects that are stored inside container objects, such as in a Map
. According to the Java API [API 2014], weak reference objects "do not prevent their referents from being made finalizable, finalized, and then reclaimed."
...
Simply facilitating garbage collection of unneeded objects through use of weak references is insufficient. Programs must also prune the recording data structure so that additional live entries can be accommodated. One pruning technique is to call the get()
method of WeakHashMap
and remove any entry that corresponds to a null
return value (polling). Use of reference queues is a more efficient method [Goetz 2005b]. However, the The implementation of WeakHashMap
in Java 7 includes a reference queue to efficiently remove entries that correspond to a null pointer value [https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/WeakHashMap.java].
...
When the garbage collector clears the reference to an object, it adds the corresponding SoftReference
object to the reference queue. The SoftReference
object remains in the reference queue until some operation is performed on the queue (such as a putpoll()
or remove()
). After such an operation, the SoftReference
SoftReference
object in the hash map is also garbage-collected:
...
[API 2014] | |||
Item 6, "Eliminate Obsolete Object References" | |||
"Memory Leak Avoidance" | |||
"Lapsed Listeners" | "Memory Leaks with Global Maps" | ||
...