Java Weak Reference

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.


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.

Ads by Google

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.


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.

This Core Java tutorial was added on 10/02/2013.



Comments on "Java Weak Reference"

  1. Google says:

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

    I like all of the points you’ve made.

  2. Baskar says:

    Hi jeo,

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

  3. neha says:

    thanks a lot :)

  4. Anonymous says:

    Appreciation for various other great article. Wherever in addition might just any individual have that form of data in such a excellent means of producing? I get a demonstration in the near future, using this program . for the hunt for such information.

  5. dsd says:

    Good , Thanks Jeo.

  6. Mohd Kose Avase says:

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

    Thanks for your explanation

  7. VENKATESH says:

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

  8. Raj says:

    Good Explanation

  9. Prabhat says:

    Thanks a lot.

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

    Thanks Again

  10. Danilo says:

    O autor não sabe o que é weak reference e nem o que é soft reference. Copiou os exemplos e quis mostrar que sabe as diferenças, mas não explicou nada com nada.

  11. Anand says:

    excellent work and great service, I really appreciate.

  12. rajinikanth says:

    very nice tutorials…

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

  14. 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?

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

  16. sultan says:


  17. Anonymous says:

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

  18. Anonymous says:

    Good Explanation

  19. Pawan says:

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

  20. vsreddy says:

    Hey Joe,

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


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


  22. ritu rai says:

    Nice Article!!!

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


  24. Kapil Kumar says:

    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.

  25. Rahul Shivsharan says:

    very good content

  26. GOOTAM says:

    Good Work Joe.. Keep it up.

  27. Shailesh says:


  28. Satnam Singh says:

    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.

  29. Anant says:

    Very nice tutorial. I like this.

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

  30. kalpesh says:

    All your tutorials are very nice :)

  31. Vinuraj says:

    Well explained,

    thanks a lot

  32. Ramesh Cheerla says:

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

  33. Ramesh says:

    Good one!

  34. 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?


Your Comment