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.

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.

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.

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.

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

«

»

Comments on “Java Weak Reference”

  1. Prabhu

    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

    Good one!

  3. Ramesh Cheerla

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

  4. Vinuraj

    Well explained,

    thanks a lot

  5. kalpesh

    All your tutorials are very nice :)

  6. Anant

    Very nice tutorial. I like this.

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

  7. Satnam Singh

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

    Good Work Joe.. Keep it up.

  9. Rahul Shivsharan

    very good content

  10. Kapil Kumar

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

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

  12. ritu rai

    Nice Article!!!

  13. Nikhil

    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

  14. vsreddy

    Hey Joe,

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

    Thanks,
    VsReddy

  15. Pawan

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

  16. Anonymous

    Good Explanation

  17. Anonymous

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

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

    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

    Hi Joe,

    Thanks for sharing your knowledge with others.

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

    Thanks a lot

  21. very nice tutorials…

  22. Anand

    excellent work and great service, I really appreciate.

  23. Danilo

    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.

  24. Prabhat

    Thanks a lot.

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

    Thanks Again
    Prabhat

  25. Raj

    Good Explanation

  26. VENKATESH

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

  27. Mohd Kose Avase

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

    Thanks for your explanation

  28. dsd

    Good , Thanks Jeo.

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

  30. neha

    thanks a lot :)

  31. Baskar

    Hi jeo,

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

  32. Google

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

    I like all of the points you’ve made.

Your Comment