Java references in nutshell

Java developers struggle to use java references and i don't blame them. The topic seldom covered by text books and even code reviews rarely give emphasis on usage of references. Why the topic is important at all? and if everybody (atleast people i have come across) is coding without it why the hell you need it?

Since you are reading this, either you are already aware of them or for the interview. Anyways, knowing references helps you manage memory better because you are able to define the behavior of the object when GC (garbage collector) is run.

Type of references:

1. Strong Reference: The normal reference in the java code is strong reference and the object referenced by strong reference is eligible for GC as soon as scope ends or reference started pointing to null in the code.
E.g. Person p = new Person();
                p = null; // will make object initialized above eligible for GC
2. Weak Reference: As name suggest these reference are weaker than the strong references.  Their are couple of ways to use them one via WeakReference call which can wrap your object and you can access the object through WeakReference.get API. Get API will be returning null id the object is GCed. (You can also use WeakHashMap)


Usage: These objects stay in the memory till the time they are referenced from any strong reference in the memory. In other words as soon as they loose accessibility from strong reference they become eligible for GC.

3. Soft Reference: Soft reference is similar to weak reference however weaker than weak references. They put the additional check on there GC eligibility, which is if GC needs space.  So basically they sits in memory still the time memory is available. Use the SoftReference API for this type of references.

Usage: These find good usage in building cache because if memory is available they don't discard the object and hence saves you the additional reload.

4. Phantom Reference: This type of reference is used to track the object if it has been garbage collected. PhantomReference get API always returns null. Object cannot be obtained from it unlike finalize() API.


Usage: So, if your object needs to be freed only when object using it becomes garbage collected than you should be using this API. Another use case is before loading  large object you want to check if the other larger object currently in memory is GCed which will help you avoid the out of memory exception.

Hope this helps :)



  

Comments

Popular posts from this blog

java.net.SocketException: Connection reset

Hide empty last column from Table/Tree Viewer

Spring: implements interface not working in @Controller