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.
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.
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();
WeakReferenceweakTextView1 = new WeakReference (textView1);
There are four types of references in Java,
above is listed in the same order as their strength.
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 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 are closed for "Java Weak Reference".
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.
Good one!
Hi Joe,
excellent explanation this very useful information with easy understanding.
Well explained,
thanks a lot
All your tutorials are very nice :)
Very nice tutorial. I like this.
Thanks a lot to provide nice explanation on the great topics.
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.
nice
Good Work Joe.. Keep it up.
very good content
+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.
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
Nice Article!!!
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
Hey Joe,
Please update the method name expungeStaleEntires() to expungeStaleEntries()
Thanks,
VsReddy
Nice article. It would have been good if you could have provided some example code
can u please provide some real time examples for 4 types references?
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..
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?
Hi Joe,
Thanks for sharing your knowledge with others.
Really it’s simple and great tutorial I have never red.
Thanks a lot
very nice tutorials…
excellent work and great service, I really appreciate.
no reference means we cannot create the object
Thanks a lot.
Your posts always contains important info and in a simple way.
Thanks Again
Prabhat
Good Explanation
Thanks for ur Sharing,
plz get me with a real time example…
Dear Joe,
As usual you have done an excellent job.
Thanks for your explanation
thanks a lot :)
Hi jeo,
Can you please give the program example for all these type. Really that make sense on the above explanation.
There’s definately a great deal to learn about this issue.
I like all of the points you’ve made.
[…] are different types of references in Java. Instances eligibility for garbage collection depends on the type of reference it […]
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…
Yes Stefan, this article requires a little bit of rewriting. I will do it in couple days.