anish jain wrote:What is the use of using weak references? what will we achieve using it?
In what situations using it will be helpful?
Please explain with the help of example
A weak reference is good for cases where a piece of data is only useful if it is actually used. And the holder of the data is not a candidate to use it.
For example, the ThreadLocal class needs a reference to the
Thread classes to store local data.... but... if the Thread object isn't used by any other threads, it is merely holding data that is no longer needed. And because it is holding the data, the thread instances won't be garbage collected, even though no other threads needs it.
To solve this, the ThreadLocal class uses a weak reference to the thread object. When all other references are gone, the data will be GC'ed from the threadlocal instance, even if the threadlocal instance is still reachable.
Henry