Can someone please point me to any good links for the same ?
Scott J Johnson
Joined: Mar 09, 2010
A strong reference is what you would normally consider a reference in java. For example, if I have the following code:
Then x is a strong reference. What this means is that the garbage collector will treat the object (an Integer object) as not able to be collected because it is referred to by a reference (namely, the variable x).
A weak reference, on the other hand, is a reference that allows us to access an object, but it doesn't force the garbage collector not to collect that object. We create a weak reference with the following:
Now, if we do the following:
The garbage collector will now treat the object behind the reference y as collectable.
So, the question is, "why would we want this?" And the answer is that sometimes, we don't want objects to stick around. This creates the Java equivalent of memory leaks. If we had a HashMap with keys that are objects, there isn't a great way to determine if the key is needed any longer. So, we can use the WeakHashMap, which uses WeakReferences as its keys. Thus, if there isn't another variable that is a (strong) reference to the key, it's removed from memory. Thus, we don't have object sticking around long after we need them.