Though the post already has some good answers ,there is just a little left which I would like to add. In the question it has been asked for
"When we use StrongReference we made its reference null to get it GC. In case of WeakRefernce also we need to make reference to object null to make it GC. What is difference between two ?".
Suppose we have an Object which is referenced by 2 strong references , x
and y
. if we make x = null
the object that was being referenced by x
is not yet eligible for garbage collection as still we have y
referencing the same. Reading y
will still result in outputting the not null object.
Now suppose we have an Object having one strong reference, say x
and one weakreference, y
. Now if we make x = null
we can be sure that the object will be eligible for garbage collection. WeakReference will not prevent this object from being garbage collected.
Invoking the get()
method on the weak reference may return null
as soon as the object is garbage collected. Hence it is advisable to always check the returned object before use.
(Important) Also we need to make that we do not hold the returned non null value in any long living hard reference (like instance fields
). If we get a weak reference then if we need then we should use weak reference as instance field and to get the object in any method, a local variable may be used to hold the returned object, it should be checked if its not null, and if so then further processing can be done using the object.
Now just an additional point for SoftReferences, they prevent the object from being garbage collected untill there is an low memory (below a threshold).