java.lang.ref
java.lang.ref
is the package of the Java programming language that provides more flexible methods for reference than are otherwise available. It is an important package, central enough to the language for the language designers to give it a name that starts with "java.lang", but it is somewhat special-purpose and not used by a lot of developers.
Java has a more expressive system of reference than most other garbage-collected languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. java.lang.ref
defines three other types of references — soft, weak, and phantom. Each type of reference is designed for a specific use.
Soft references can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable) but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector.
Weak references are used to implement weak maps. An object that is not strongly or softly reachable but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class WeakHashMap
. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool.
Phantom references reference objects that have been marked for garbage collection but have not yet been finalized. This allows for more flexible cleanup than is possible with the finalization mechanism alone.
java.lang.ref
also defines a class, ReferenceQueue<T>
, which can be used in each of the applications discussed above to keep track of objects that have changed reference type.