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

95,744

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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

Solution 5

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

Share:
95,744

Related videos on Youtube

M. Justin
Author by

M. Justin

I am a professional software developer with over a decade of experience with Java, Spring, and numerous other technologies.

Updated on August 01, 2021

Comments

  • M. Justin
    M. Justin almost 3 years

    I have read this article about different types of references in Java (strong, soft, weak, phantom), but I don't really understand it.

    What is the difference between these reference types, and when would each type be used?

  • Saurabh Patil
    Saurabh Patil over 9 years
    I think this is wrong - "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." It is not necessarily that way, how can you be so sure that they occur in consecutive run of GC? GC can allow soft referenced objects to live even in 2nd run and 3rd run too. There is not documentation for it, if there is then please mention the link specifying.
  • Saurabh Patil
    Saurabh Patil over 9 years
    Also, your answer is a little vague, look at this sentence ' 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.' - he is clearly asking about the difference and not similarities, all these words add more confusion than clarity to the topic.
  • Sabya
    Sabya about 9 years
    @SaurabhPatil -- Missed your comment. Here goes the answers . 1. "he is clearly asking about the difference and not similarities" -- Refer to the description of the question (not "only" the title) "Please give me some advice, and please give me some example to describe". 2. "But you can say that it holds the object a bit more .... " I think SOF gives an option to down-vote and give new answers too.
  • Theodore Murdock
    Theodore Murdock over 8 years
    While everything in this answer looks correct, it also looks to me like there may be an error on the linked webpage. The Javadoc for package java.lang.ref and that for PhantomReference suggest that an object is not garbage collected until after it is no longer "phantom reachable", implying that (unlike SoftReference) a PhantomReference must be dequeued before the object it refers to can be garbage collected...and its being enqueued does not indicate that the associated memory has been freed.
  • Theodore Murdock
    Theodore Murdock over 8 years
    For the record, I would much rather live in a world where that blog post is correct.
  • Leliel
    Leliel about 8 years
    @TheodoreMurdock The javadoc is correct. A phantom reference does not impede garbage collection at all. Once an object is enqueued, it cannot be saved even by a finalizer, as finalizers have already run. It's dead, but not yet gone.
  • Theodore Murdock
    Theodore Murdock about 8 years
    @Leliel Actually, a phantom reference does in fact impede garbage collection after it is enqueued...I realized this recently when a bug caused a cleanup thread to exit early. The existence of phantom references was sufficient to ensure that every phantom referenced object was retained in my heap dump, unavailable for collection...if you fail to process the queue, or fail to make the phantom reference eligible for gc when processing the queue (and do not clear() the phantom reference), then your memory leak will include both the phantom reference and the referenced object.
  • filemonczyk
    filemonczyk over 5 years
    you wrote that weak refrences will be GC'ed in next cycle if not refrenced from other refrences... but should not happen the same thing to stron refrences? if stron refrence is not accessed in any way then gets cleared... then if so then where is the difference again ... ? #confused
  • Naresh Joshi
    Naresh Joshi over 5 years
    If an object is getting referred from let's say s1 (strong) and s2 (strong), the object will not be eligible for garbage collection until both s1 and s2 are dereferenced but if the object is getting referred from s1 (weak) and s2 (strong) then object will be eligible for garbage collection in the next GC cycle when it gets dereferenced from s2 only, because s1 is a weak reference and if object does not have any other reference except the weak one it is eligible for GC
  • theRiley
    theRiley over 3 years
    "Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable." source: Java8 API Docs PhantomReference
  • samshers
    samshers over 3 years
    adding to the Q: strongRef --> weakRef --> objA. Now, will objA will be GCed or not, as it has an indirect ref from strongRef.
  • samshers
    samshers over 3 years
    adding to the Q: strongRef --> weakRef --> objA. Now, will objA will be GCed or not, as it has an indirect ref from strongRef.
  • froh42
    froh42 almost 3 years
    Damn, now I want to hear a story starting with "A soft reference comes to a bar ..."
  • Manan Shah
    Manan Shah about 2 years
    Upvoted for the "waiter" story... So easy to understand by the story...