WeakHashMap
uses weak references to hold its keys, making it one of the few classes able to respond to the fluctuating memory requirements of the JVM.
Specifically, we want to handle the situation where the
deregisterObject()
method is not called, but the registered object is no longer referenced anywhere in the application, except by our internal Map
. This situation is precisely what WeakHashMap
was designed for. The keys entered into a WeakHashMap
are held usingWeakReferences
. This allows the garbage collector to collect the keys if there are no other strong references to those keys elsewhere in the application (for more details about strong and weak references in Java, see the "Further resources" section at the end of this article). After the keys have been collected, the values are also dereferenced from the WeakHashMap
, and can also be garbage collected if they are not referred to elsewhere in the application.Using WeakHashMap as a Cache
WeakHashMap
can also be used fairly straightforwardly as a cache that can be cleared automatically when JVM memory is low. The only difference is in needing the keys to be objects which can be equal to other keys of the same class.
No comments:
Post a Comment