Jump to content

Java.lang.ref: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Added Javadoc links, some minor edits
Merged page to Java Platform, Standard Edition#java.lang.ref and changed page to a redirect
Line 1: Line 1:
{{lowercase|title=java.lang.ref}}
#REDIRECT [[Java Platform, Standard Edition#java.lang.ref]]

'''<code>java.lang.ref</code>''' is the [[Packages in Java|package]] of the [[Java programming language]] that provides more flexible methods for [[Reference (computer science)|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 collection (computer science)|garbage-collected]] [[Programming language|languages]], which allows for special behavior for garbage collection. A normal reference in Java is known as a ''strong reference''. The {{Javadoc:SE|package=java.lang.ref|java/lang/ref}} package defines three other types of references &mdash; ''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 <code>WeakHashMap</code>. 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.

<code>java.lang.ref</code> also defines a class, {{Javadoc:SE|class=ReferenceQueue&lt;T&gt;|java/lang/ref|ReferenceQueue}}, which can be used in each of the applications discussed above to keep track of objects that have changed reference type.

[[Category:Java programming language]]

Revision as of 22:33, 23 February 2006