0

why soft/weak/phantom reference is required instead of making object is null. I am not having clear idea why do we need to use these references.

As far as my understanding the inner object may be null but the outer object is reachable then inner object wont be garbage collected, to collect the inner object we need to use the soft/weak/phantom reference. Is this correct or do we have some other reason to use it?

I read in one of the stack over flow post the modern JVM are taking care of this inner object is null then garbage collected, i cannot able to find the more details for this.

Thanks in advance.

user2724215
  • 165
  • 5
  • 16

1 Answers1

0

Data structures like WeakHashMap uses WeakReference on the keys.

Basically the idea is that if in your code there is a reference to a key the value corresponding to that key is mantained in the Map.

If no more references are present on your code to that key the value associated can be a candidate for the garbage collector.

From java doc:

Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

This behaviour can't be obtained without a WeakReference

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • The WeakHashMap i am clear, what about the objects used for soft/weak/phantom referenece when it will be required? Only for clearing the inner objects we need to use these references ? – user2724215 Sep 29 '15 at 14:15
  • Note that "in your code" should be understood as accessible by any active Thread (as a stack variable, a static or a ThreadLocal) – Benoît Sep 29 '15 at 14:35
  • Your code means not in the WeakHashMap code. Any code the user of the WeakHashMap has written. – Davide Lorenzo MARINO Sep 29 '15 at 14:45
  • Check this post: http://stackoverflow.com/questions/11397522/when-to-use-weak-and-phantom-references-in-java – Chaitanya P Oct 05 '15 at 11:28
  • Soft Reference -applications in Cache. Why? JVM let us say runs out of memory, then it needs quick ways to free memory from areas which the program designer feels would be not really needed/critical instead of landing at out of memory exception, then soft references are the ones which can be used to state to JVM that you can free them when memory is your priority for another strong reference object to be allocated. For weak and phantom references, link I gave above covers all you need. – Chaitanya P Oct 05 '15 at 11:36