<rdf:RDF
    xmlns:s='http://snipsnap.org/rdf/snip-schema#'
    xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
    xml:base='http://pabrantes.net/blog/rdf'>
    <s:Snip rdf:about='http://pabrantes.net/blog/rdf#start/2007-09-16/1'
         s:name='start/2007-09-16/1'
         s:cUser='pabrantes'
         s:oUser='pabrantes'
         s:mUser='pabrantes'>
        <s:content>1 Java Programming: References&apos; Package {anchor:Java Programming: References&apos; Package}&#xD;&#xA;This time I&apos;ll be writing about an interesting - sometimes not very well known - subject regarding the Java programming language, __references__.\\ &#xD;&#xA;Since Java SDK 1.2, Sun introduced the ~~{link:java.lang.ref|url=http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/package-summary.html}~~ package. In this post I&apos;ll be explaining concepts regarding references in Java, what kind of references are available in the ~~java.lang.ref~~ package and possible uses for each one of the references&apos; types. &#xD;&#xA; &#xD;&#xA;__The Basics__&#xD;&#xA;&#xD;&#xA;In Java all objects are referred by references, in a simplistic way a reference can be seen as a pointer to the actual object which is in the JVM heap. This means that for example when we have the following code:&#xD;&#xA;&#xD;&#xA;{code}&#xD;&#xA;  ExampleObject exampleObject = new ExampleObject();&#xD;&#xA;{code}&#xD;&#xA;&#xD;&#xA;The variable __exampleObject__ will not hold the object instance itself but, a reference that holds the place where the actual instance is.\\&#xD;&#xA;An object itself may have various references to itself or none. The references to him can be from different types and those references or the lack of it will influence the actions of the Garbage Collector (GC).&#xD;&#xA;&#xD;&#xA;Since I&apos;m talking about references I&apos;ll point out an important part of the Java language. A trick question that is usually asked regarding references is the following: when passing parameters to a method are they passed by reference or by value?\\&#xD;&#xA;It&apos;s usual to see the following answer - or at least I&apos;m used to get this answer-, &quot;~~Everything is passed by referenced except primitive types which are passed by value~~&quot;, I myself gave this answer for a long time. But this is __wrong__.\\&#xD;&#xA;Parameters are __always__ passed by value. This happens because, like I said  variables only hold a reference not the actual object. So when using it as a parameter for a method the reference is copied - the object starts having one more reference to it - and is used as the method parameter. &#xD;&#xA;&#xD;&#xA;With references a new concept is introduce, the concept of object __reachability__. This is an important concept because it is what allows the GC to decide what should be done.&#xD;&#xA;&#xD;&#xA;When a Java program is executed, one or more threads start performing instructions. &#xD;&#xA;Among the type of instructions is the definition of new objects. The references to this objects are said to belong to the root graph of references and their objects are said to be reachable. An object is said to be reachable if and only if there&apos;s at least one path in the root reference graph that leads to at least one of it&apos;s references.&#xD;&#xA;&#xD;&#xA;{image:img=start/2007-09-16/1/reachability.png|align=float-left} As an example, a simple scenario is described in the figure at the left. As it can be seen ~~Object1~~ and ~~Object3~~ are reachable since there are references to them, Object 2 is also reachable since Object1 is reachable and has a reference to ~~Object2~~.\\&#xD;&#xA;On the other hand, objects 4 to 6 are unreachable, which means they can be garbage collected (GCed). When an object is said to be GCed it means that the GC claims the memory the object is using and after a finalization process it clears the memory for future allocations. &#xD;&#xA;&#xD;&#xA;When an object is reachable it won&apos;t be collected by the GC, except in special cases. A &quot;standard&quot; reference in Java is called a __strong__ reference and when an object has at least one of these references it will __never__ be collected. But, if the references available in the reference&apos;s package are used instead, weaker references will be created, that according to certain rules will allow the objects to be GCed. This is the main reason of the ~~java.lang.ref~~ package, __allow the developer to control the strength of the reference__.&#xD;&#xA; &#xD;&#xA;After this short introduction is now time to present the four types of references available in Java.&#xD;&#xA;&#xD;&#xA;__Java References__&#xD;&#xA;&#xD;&#xA;{image:img=start/2007-09-16/1/refpackage.png|align=float-right}&#xD;&#xA;Like I&apos;ve been saying, Java supports four different kinds of references, being the &quot;standard&quot; one called strong reference. Strong references are not represented itself by an object from the ~~java.lang.ref~~ package, rather by the lack of existing of any of those objects in the reference path to the object. &#xD;&#xA;&#xD;&#xA;The other three types are implemented as Reference&apos;s subclasses and they are Soft Reference, Weak Reference and Phantom Reference - see figure on the right. These references are the ones who make the ~~java.lang.ref~~ package.&#xD;&#xA;The order of strength defined is the following, from the strongest to the weakest:&#xD;&#xA;&#xD;&#xA;1. Strong reference&#xD;&#xA;1. Soft reference&#xD;&#xA;1. Weak reference&#xD;&#xA;1. Phantom reference&#xD;&#xA;&#xD;&#xA;As said before an object may have various references to it. Since the references can be from any of the types mentioned above, it has to be clear when can an object be said to be softly reachable, weakly reachable and phantomly reachable. This is important because like I previously said the GC uses this information to perform its work. Since the relation of order between references has been already presented it&apos;s easy to present the solution.\\ &#xD;&#xA;An object is said to be reachable by a certain type - where type is strong, soft, weak or phantom - if that type is the weakest link in the strongest path to reach the object.\\ &#xD;&#xA;Let&apos;s see a few examples to make the last statement more clear. Please remember that the strong reference sphere does not represent an object but the lack of any object from the reference package, I&apos;ve chosen to still represent it as a sphere to have graphical coherence.&#xD;&#xA;{image:img=start/2007-09-16/1/referenceTypes.png|align=float-left} Using the example scenarios on the image it can said the following:&#xD;&#xA;&#xD;&#xA;__Case 1__: This is the regular case where Object is said to be __strongly__ reachable.&#xD;&#xA;&#xD;&#xA;__Case 2__: There are two paths to Object, so the strongest one is chosen, which is the one with the strong reference hence the object is __strongly__ reachable.&#xD;&#xA;&#xD;&#xA;__Case 3__: Once again there are two paths to the Object, the strongest one is the Weak Reference (since the other one is a Phantom Reference), so the object is said to be __weakly__ reachable.&#xD;&#xA;&#xD;&#xA;__Case 4__: There is only one path and the weakest link is a weak reference, so the object is __weakly__ reachable.&#xD;&#xA;&#xD;&#xA;__Case 5__: Only one path and the weakest link is the phantom reference hence the object is __phantomly__ reachable.&#xD;&#xA;&#xD;&#xA;__Case 6__: There are now two paths and the strongest path is the one with a soft reference, so the object is now said to be __softly__ reachable.&#xD;&#xA;&#xD;&#xA;After presenting the different levels of reachability an object can have, it&apos;s time to explain what happens in each of those levels.&#xD;&#xA;The GC is a part of JVM that looks through the memory in order to find objects that are no longer reachable and free their memory for reuse. But  when the GC finds an object that still contains references it all depends on the object&apos;s reachability. &#xD;&#xA;&#xD;&#xA;If an object...&#xD;&#xA;&#xD;&#xA;* ... is __strongly__ reachable, it won&apos;t, in any circumstances, be reclaimed by the GC.&#xD;&#xA;&#xD;&#xA;* ... is __softly__ reachable, the GC may choose or not to reclaim the memory, it depends if the GC thinks the memory will or not be needed. But, all softly reachable objects will be reclaimed before an OutOfMemoryException is thrown.&#xD;&#xA;&#xD;&#xA;* ... is __weakly__ reachable, the GC will __always__ reclaim the memory.&#xD;&#xA;&#xD;&#xA;* ... is __phantomly__ reachable, it means the object already has been finalized but not yet reclaimed, so the GC enqueues it in a {link:ReferenceQueue|url=http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/ReferenceQueue.html} for post-finalization processing.&#xD;&#xA; &#xD;&#xA;After presenting the different kinds of references and how the GC interacts with them, it&apos;s time to explore the uses of the three non-strong references. Even if the uses can be unlimited, there are a few problems that can easily be solved using this reference objects. Here are some examples:&#xD;&#xA;&#xD;&#xA;__Uses for SoftReference__&#xD;&#xA;&#xD;&#xA;* The creation of a memory cache using SoftReferences for the values. Using Soft References for caches gives two main advantages:&#xD;&#xA;&#xD;&#xA;** Dynamical behaviour for the cache, if the memory is needed objects that are only referenced in the cache will be reclaimed.&#xD;&#xA;** When there&apos;s space in memory, even objects that are only in the cache will be kept.&#xD;&#xA;&#xD;&#xA;* Proxies, the proxy object is a strong reference but the reference it contains to the actual object is a soft reference. This allows that the object gets reclaimed when there is memory shortage.&#xD;&#xA;&#xD;&#xA;__Uses for WeakReference__&#xD;&#xA;&#xD;&#xA;* Web applications sometimes create objects that are used by the user but there&apos;s no way to tell if they are still being used or not, like having objects that represent images. Using a Weak Reference to represent this objects might be a good call. Due to this those objects will always be reclaimed when the GC runs.&#xD;&#xA;&#xD;&#xA;__Uses for PhantomReference__&#xD;&#xA;&#xD;&#xA;* Extending the behaviour of an object finalization, such as inform a remote system that a given object ceased to exist. Phantom References are the only references that always have to be created with a ReferenceQueue because they&apos;re directly put in such queue to clear the object. Although on that queue other operations can be done extending the post-finalization process.&#xD;&#xA;&#xD;&#xA;Those were only a few simple examples, the important is to know that such mechanism is available in the Java, imagination is now the limit for using such features.\\&#xD;&#xA;Hope it has been helpful.</s:content>
        <s:mTime>2007-09-16 21:55:52.179</s:mTime>
        <s:cTime>2007-09-16 21:37:44.987</s:cTime>
        <s:comments
             rdf:type='http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag'/>
        <s:snipLinks>
            <rdf:Bag>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2007-09-26/1'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2007-10-22/1'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2006-08-27/1'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2007-07-09/1'/>
                <rdf:li rdf:resource='#snipsnap-notfound'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2006-05-10/1'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2007-06-10/1'/>
                <rdf:li rdf:resource='#my_snipsnap_fork_feature_list'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2007-10-24/1'/>
                <rdf:li rdf:resource='http://pabrantes.net/blog/rdf#start/2007-07-23/1'/>
            </rdf:Bag>
        </s:snipLinks>
        <s:attachments>
            <rdf:Bag>
                <rdf:li>
                    <s:Attachment rdf:about='http://pabrantes.net/blog/space/start/2007-09-16/1/reachability.png'
                         s:fileName='reachability.png'
                         s:contentType='image/png'
                         s:size='21737'>
                        <s:date>Sun Sep 16 21:38:42 WEST 2007</s:date>
                    </s:Attachment>
                </rdf:li>
                <rdf:li>
                    <s:Attachment rdf:about='http://pabrantes.net/blog/space/start/2007-09-16/1/referenceTypes.png'
                         s:fileName='referenceTypes.png'
                         s:contentType='image/png'
                         s:size='57857'>
                        <s:date>Sun Sep 16 21:38:59 WEST 2007</s:date>
                    </s:Attachment>
                </rdf:li>
                <rdf:li>
                    <s:Attachment rdf:about='http://pabrantes.net/blog/space/start/2007-09-16/1/refpackage.png'
                         s:fileName='refpackage.png'
                         s:contentType='image/png'
                         s:size='16811'>
                        <s:date>Sun Sep 16 21:39:11 WEST 2007</s:date>
                    </s:Attachment>
                </rdf:li>
            </rdf:Bag>
        </s:attachments>
    </s:Snip>
</rdf:RDF>
