Inside Paulo Abrantes' head
[ start | index | login or register ]
start > 2007-09-16 > 1

Java Programming: References' Package

Created by pabrantes. Last edited by pabrantes, 312 days ago. Viewed 1,359 times. #5
[diff] [history] [edit] [rdf]
labels
attachments
reachability.png (21737)
referenceTypes.png (57857)
refpackage.png (16811)

Java Programming: References' Package

This time I'll be writing about an interesting - sometimes not very well known - subject regarding the Java programming language, references.
Since Java SDK 1.2, Sun introduced the >>java.lang.ref package. In this post I'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' types.

The Basics

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:

ExampleObject exampleObject = new ExampleObject();

The variable exampleObject will not hold the object instance itself but, a reference that holds the place where the actual instance is.
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).

Since I'm talking about references I'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?
It's usual to see the following answer - or at least I'm used to get this answer-, "Everything is passed by referenced except primitive types which are passed by value", I myself gave this answer for a long time. But this is wrong.
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.

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.

When a Java program is executed, one or more threads start performing instructions. 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's at least one path in the root reference graph that leads to at least one of it's references.

reachability 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.
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.

When an object is reachable it won't be collected by the GC, except in special cases. A "standard" 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'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.

After this short introduction is now time to present the four types of references available in Java.

Java References

refpackage Like I've been saying, Java supports four different kinds of references, being the "standard" 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.

The other three types are implemented as Reference'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. The order of strength defined is the following, from the strongest to the weakest:

  1. Strong reference
  2. Soft reference
  3. Weak reference
  4. Phantom reference
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's easy to present the solution.
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.
Let'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've chosen to still represent it as a sphere to have graphical coherence. referenceTypes Using the example scenarios on the image it can said the following:

Case 1: This is the regular case where Object is said to be strongly reachable.

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.

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.

Case 4: There is only one path and the weakest link is a weak reference, so the object is weakly reachable.

Case 5: Only one path and the weakest link is the phantom reference hence the object is phantomly reachable.

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.

After presenting the different levels of reachability an object can have, it's time to explain what happens in each of those levels. 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's reachability.

If an object…

  • … is strongly reachable, it won't, in any circumstances, be reclaimed by the GC.
  • … 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.
  • … is weakly reachable, the GC will always reclaim the memory.
  • … is phantomly reachable, it means the object already has been finalized but not yet reclaimed, so the GC enqueues it in a >>ReferenceQueue for post-finalization processing.
After presenting the different kinds of references and how the GC interacts with them, it'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:

Uses for SoftReference

  • The creation of a memory cache using SoftReferences for the values. Using Soft References for caches gives two main advantages:
    • Dynamical behaviour for the cache, if the memory is needed objects that are only referenced in the cache will be reclaimed.
    • When there's space in memory, even objects that are only in the cache will be kept.
  • 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.
Uses for WeakReference
  • Web applications sometimes create objects that are used by the user but there'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.
Uses for PhantomReference
  • 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're directly put in such queue to clear the object. Although on that queue other operations can be done extending the post-finalization process.
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.
Hope it has been helpful.
no comments | post comment
Who am I?
paulo-roca2My name is Paulo Abrantes AKA pabrantes and I'm a software developer. I'm currently employed at >>CIIST working as a Java developer in >>FenixEDU.

This blog is mostly about Java programming, domain driven design and snipsnap bliki developing. Everything written in this blog is my personal opinion and it may not reflect the opinions of my employer and co-workers.


Blog subscription
subscribe by rss subscribe by email

Links
>> Home
>> Paulo's Profile
>> Post History
>> Add to Technorati Favorites
>> Paulo's Photo Gallery
>> WishList
>> Posting without Login

Search Blog
Fellow Bloggers

Recent Posts

Java Programming: Bytecode Injection
Intermission: Sorry For Downtime
Software Developing: Studying The Bliki Domain Model
SnipSnap Developing: Trying to settle a roadmap
System Administration: Load Balancing with Apache
Blogging: Two years have passed
Software Developing: The SnipSnap Saga
Java Programming: Getting your code spicy with Groovy
Software Developing: Fluent Interfaces
Software Developing: Implementing a ShoutBox on SnipsSnip
Software Developing: SnipSnap, SnipIt and SnipSnip
Java Programming: Proxies and Access Control
Java Programming: Proxies and References
Java Programming: References' Package
YALM: Yet Another Layout Modification

For older posts, please refer to post-history for a complete Post History

Logged in Users: (0)
… and 17 Guests.
This is a modified version of snipsnap.org created by >>Paulo Abrantes