Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: difference between strong/soft/weak/phantom reference

People also ask

What are strong soft weak and phantom references in Java?

An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable. So in brief: Soft references try to keep the reference. Weak references don't try to keep the reference. Phantom references don't free the reference until cleared.

What is weak reference and soft reference in Java?

A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.

What are strong and weak references?

A strong reference is what is explained above and is the default behaviour. A weak reference allows a variable to hold the reference to an object without incrementing the reference counter.


Java provides two different types/classes of Reference Objects: strong and weak. Weak Reference Objects can be further divided into soft and phantom.

  • Strong
  • Weak
    • soft
    • phantom

Let's go point by point.

Strong Reference Object

StringBuilder builder = new StringBuilder();

This is the default type/class of Reference Object, if not differently specified: builder is a strong Reference Object. This kind of reference makes the referenced object not eligible for GC. That is, whenever an object is referenced by a chain of strong Reference Objects, it cannot be garbage collected.

Weak Reference Object

WeakReference<StringBuilder> weakBuilder = new WeakReference<StringBuilder>(builder);

Weak Reference Objects are not the default type/class of Reference Object and to be used they should be explicitly specified like in the above example. This kind of reference makes the reference object eligible for GC. That is, in case the only reference reachable for the StringBuilder object in memory is, actually, the weak reference, then the GC is allowed to garbage collect the StringBuilder object. When an object in memory is reachable only by Weak Reference Objects, it becomes automatically eligible for GC.

Levels of Weakness

Two different levels of weakness can be enlisted: soft and phantom.

A soft Reference Object is basically a weak Reference Object that remains in memory a bit more: normally, it resists GC cycle until no memory is available and there is risk of OutOfMemoryError (in that case, it can be removed).

On the other hand, a phantom Reference Object is useful only to know exactly when an object has been effectively removed from memory: normally they are used to fix weird finalize() revival/resurrection behavior, since they actually do not return the object itself but only help in keeping track of their memory presence.

Weak Reference Objects are ideal to implement cache modules. In fact, a sort of automatic eviction can be implemented by allowing the GC to clean up memory areas whenever objects/values are no longer reachable by strong references chain. An example is the WeakHashMap retaining weak keys.


Weak Reference :

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.

Soft Reference :

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

Phantom Reference :

A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead.

This text was extracted from: https://weblogs.java.net/blog/2006/05/04/understanding-weak-references


The simple difference between SoftReference and WeakReference is provided by Android Developer.

The difference between a SoftReference and a WeakReference is the point of time at which the decision is made to clear and enqueue the reference:

  • A SoftReference should be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory.

  • A WeakReference may be cleared and enqueued as soon as is known to be weakly-referenced.


This article can be super helpful to understand strong, soft, weak and phantom references.


To give you a summary,

If you have a strong reference to an object, then the object can never be collected/reclaimed by GC (Garbage Collector).

If you only have weak references to an object (with no strong references), then the object will be reclaimed by GC in the very next GC cycle.

If you only have soft references to an object (with no strong references), then the object will be reclaimed by GC only when JVM runs out of memory.

We create phantom references to an object to keep track of when the object gets enqueued into the ReferenceQueue. Once you know that you can perform fine-grained finalization. (This would save you from accidentally resurrecting the object as phantom-reference don't give you the referrant). I'd suggest you reading this article to get in-depth detail about this.


So you can say that, strong references have ultimate power (can never be collected by GC)

Soft references are powerful than weak references (as they can escape GC cycle until JVM runs out of memory)

Weak references are even less powerful than soft references (as they cannot escape any GC cycle and will be reclaimed if object have no other strong reference).


Restaurant Analogy

  • Waiter - GC
  • You - Object in heap
  • Restaurant area/space - Heap space
  • New Customer - New object that wants table in restaurant

Now if you are a strong customer (analogous to strong reference), then even if a new customer comes in the restaurant or what so ever happnes, you will never leave your table (the memory area on heap). The waiter has no right to tell you (or even request you) to leave the restaurant.

If you are a soft customer (analogous to soft reference), then if a new customer comes in the restaurant, the waiter will not ask you to leave the table unless there is no other empty table left to accomodate the new customer. (In other words the waiter will ask you to leave the table only if a new customer steps in and there is no other table left for this new customer)

If you are a weak customer (analogous to weak reference), then waiter, at his will, can (at any point of time) ask you to leave the restaurant :P


The three terms that you have used are mostly related to Object's eligibility to get Garbage collected .

Weak Reference :: Its a reference that is not strong enough to force the object to remain in memory . Its the garbage collector's whims to collect that object for garbage collection. You can't force that GC not to collect it .

Soft Reference :: Its more or less same like the weak reference . But you can say that it holds the object a bit more strongly than the weak reference from garbage collection.

If the Garbage collectors collect the weak reference in the first life cycle itself, it will collect the soft reference in the next cycle of Garbage collection.

Strong Reference :: Its just opposite to the above two kind of references . They are less like to get garbage collected (Mostly they are never collected.)

You can refer to the following link for more info :

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ref/Reference.html


4 degrees of reference - Strong, Weak, Soft, Phantom

Strong - is a kind of reference, which makes the referenced object not eligible for GC. builder classes. eg - StringBuilder

Weak - is a reference which is eligible for GC.

Soft - is a kind of reference whose object is eligible for GC until memory is avaiable. Best for image cache. It will hold them till the memory is available.

Phantom - is a kind of reference whose object is directly eligible for GC. Used only to know when an object is removed from memory.

uses:

  1. Allows you to identify when an object is exactly removed from memory.

  2. when finalize() method is overloaded, then GC might not happen in timely fashion for GC eligible objects of the two classes. So phantom reference makes them eligible for GC before finalize(), is why you can get OutOfMemoryErrors even when most of the heap is garbage.

Weak references are ideal to implement the cache modules.