Java Weak Reference

Last modified on November 2nd, 2014 by Joe.

Releasing unused objects for garbage collection can be done efficiently using java weak reference. Yes. weak reference is related to garbage collection. In java we need to not anything explicitly for garbage collection (GC), this memory management overhead is taken care by java run-time itself.

Then what is the use of java weak reference? Let us see an example scenario, which will help us understand the problem in detail. Before that, we should be aware there are four types of references in java and they are strong reference, weak reference, soft reference and phantom reference.

Weak Reference

When there are one or more reference to an object it will not be garbage collected in Java. But this rule depends on what type of reference it is. If an object has only weak reference associated with other objects, then it is a valid candidate for garbage collection.

Let us take a sample scenario to understand it better. Let TextView be an object (recently programming in Android and so using its class for example :-)) and we will have program generated ids used for its identification. These ids are used in some other object for referencing the TextViews.

...
Map textViewIdMap = new HashMap();
textViewIdMap.put(textView1, iD1);
textViewIdMap.put(textView2, iD2)
...

Key is TextView object and value is the Id. Now, during the execution of the program we have removed a TextView object say textView1. We do not require that view object so we have made it null. Now, what will happen to the key-value pair(textView1, iD1) stored in HashMap. This pair as of now makes no sense and it is not required as that textview itself is null.

So, programmatic we need to ensure that, when a textView is removed then its corresponding entry in the map should be removed. Only then, that object becomes a candidate for garbage collection. Otherwise, even though it is not used at run-time, this stale object will not be garbage collected.

WeakHashMap

There is a predefined Map which uses weak reference. This is an implementation of Map interface and exactly same as HashMap but with only difference of weakrefernce. Key-value pairs extext WeakReference class.

...
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>
...

In WeakHashMap there is a private method name expungeStaleEntires(), which is used to remove stale entries as given in above scenario. This method is internally used before get/getEntry/put/resize/size /…. all methods. Only after expunge done the regular operation is done. It just makes a stale entry ‘null’ and releases it for garbage collection. You may read its source code for more detail.

Strong Reference vs Weak Reference

Strong reference is not something new, it is nothing but what we use in our daily programming. The default reference for objects. Strong reference is strongest of all references, if there there is a strong reference garbage collecter will not even come to this object :-)

StringBuilder iD1 = new StringBuilder();

Strong Reference

WeakReference weakTextView1 = new WeakReference(textView1);

Weak Reference

Types of References in Java

There are four types of references in Java,

  1. Strong Reference
  2. Soft Reference
  3. Weak Reference
  4. Phantom Reference

above is listed in the same order as their strength.

References

Soft Reference

Soft Reference is slightly stronger that weak reference. Soft reference allows for garbage collection, but begs the garbage collector to clear it only if there is no other option. That is, it is eligible for garbage collection, but garbage collector can remove it based on the memory crunch it has. If it is left with little memory and it is in a position to reclaim memory, then it will collect the soft references.

Phantom Reference

Phantom reference is different from soft/weak reference. This can never be reached before it is cleared in the program. Calling the get() on it return null always. When a phantom referenced object is garbage collected, it is notified via the ReferenceQueue. We can use this to find when it is garbage collected and no use other than that.

Comments on "Java Weak Reference"

  1. Prabhu says:

    Hi Joe,
    All your tutorials are excellent. Very easy to understand. Thousand Thanks.

    Can you take java tuition/ classes, I am in Chennai?

    Thanks,
    Prabhu.

  2. Ramesh says:

    Good one!

  3. Ramesh Cheerla says:

    Hi Joe,
    excellent explanation this very useful information with easy understanding.

  4. Vinuraj says:

    Well explained,

    thanks a lot

  5. kalpesh says:

    All your tutorials are very nice :)

  6. Anant says:

    Very nice tutorial. I like this.

    Thanks a lot to provide nice explanation on the great topics.

  7. Satnam Singh says:

    Dear,
    You are doing great job by sharing your knowledge with others. Do one more favour for us just share that what are the resources of your up to date knowledge that you often follows (Articles, Web Sites, books, Links, Magazines etc). If possible mail me. Thanks in advance.

  8. Shailesh says:

    nice

  9. GOOTAM says:

    Good Work Joe.. Keep it up.

  10. Rahul Shivsharan says:

    very good content

  11. Kapil Kumar says:

    +1.
    Keep up the good work.

    Can you please write more on Android Framework side also ?

    May be on Window Manger / View Groups / Event Handling Flow from system to App etc.
    Thank you.

  12. Rahul Shelke says:

    Hi Joe,

    Nice references. I really love your tuts as well as information.

    FYI: The URL reference for “Reference Queue” is broken somehow, in Phantom Reference description. Can you please fix it, that would be helpful.

    Thanks.
    Rahul

  13. ritu rai says:

    Nice Article!!!

  14. Nikhil says:

    Hi Joe
    I am going through your articles they are quite comprehensive and easy to understand. Keep up the good work friend.

    Just a small request:
    what are the resources of your up to date knowledge that you often follows (Articles, Web Sites, books, Links, Magazines etc). If possible mail me.

    Thanks

  15. vsreddy says:

    Hey Joe,

    Please update the method name expungeStaleEntires() to expungeStaleEntries()

    Thanks,
    VsReddy

  16. Pawan says:

    Nice article. It would have been good if you could have provided some example code

  17. Anonymous says:

    can u please provide some real time examples for 4 types references?

  18. Dilip says:

    The given diagram is giving me a wrong impression. why Object A or B? If we delete an entry from A the same object will update… please clarify me if I am wrong..

  19. Bharath786 says:

    What happens if the weakhashmap contains a entry like this

    Object x –> Object y

    x does not have any references
    y does not have any references

    do both of them get garbage collected same time or is the action based on key references?

    does key get garbage collected first and then value gets garbage collected in next cycle?

  20. Manikandan Palanisamy says:

    Hi Joe,

    Thanks for sharing your knowledge with others.

    Really it’s simple and great tutorial I have never red.

    Thanks a lot

  21. rajinikanth says:

    very nice tutorials…

  22. Anand says:

    excellent work and great service, I really appreciate.

  23. Anonymous says:

    no reference means we cannot create the object

  24. Prabhat says:

    Thanks a lot.

    Your posts always contains important info and in a simple way.

    Thanks Again
    Prabhat

  25. Raj says:

    Good Explanation

  26. VENKATESH says:

    Thanks for ur Sharing,
    plz get me with a real time example…

  27. Mohd Kose Avase says:

    Dear Joe,
    As usual you have done an excellent job.

    Thanks for your explanation

  28. neha says:

    thanks a lot :)

  29. Baskar says:

    Hi jeo,

    Can you please give the program example for all these type. Really that make sense on the above explanation.

  30. Google says:

    There’s definately a great deal to learn about this issue.

    I like all of the points you’ve made.

  31. […] are different types of references in Java. Instances eligibility for garbage collection depends on the type of reference it […]

  32. Stefan says:

    I think, I am not getting the idea behind the “Weak Reference” part of this tutorial…. So a weak reference is an object that can not be garbage collected or…?
    If so the term weak reference is a bit confusing and means the opposite of at least the way I see it should be…

  33. Joe says:

    Yes Stefan, this article requires a little bit of rewriting. I will do it in couple days.

Comments are closed for "Java Weak Reference".