0

Please explain what WeakReferences are used for. I usually do understand Java concepts, but this one is giving me trouble.

I do understand what WeakReferences are, but their usage and nature is a little vague inside my head. I am not able to visualize a correct scenario wherein using WeakReferences becomes a necessity.

I also know that a WeakHashMap is related to WeakReferences where a row which contains a null key, gets automatically removed. I can't visualize how can this be, that I have a WeakHashMap somewhere, and some other process nullifies a key, and then WeakHashMap saves the day by removing that row.

Also this article that everyone refers to, does not provide a case study that would help me understand.

If anyone out there can come up with a scenario and give me some understanding into this, I would be really grateful.

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Muhammad Ahmed AbuTalib
  • 4,080
  • 4
  • 36
  • 59
  • The "*When strong references are too strong*" section of that article describes a couple of scenarios where weak references are useful... – Oliver Charlesworth Oct 20 '13 at 13:38
  • 1
    To get an answer here, please pose a specific, practical, question. What problem do you have that might be solved with these classes? – bmargulies Oct 20 '13 at 13:40

1 Answers1

2

Weak references are basically used when you don't want the object to "stick" around if no one else is pointing to it. One very common use case which I believe helps when thinking of weak references is the use of weak hash map for maintaining canonical mapping.

Consider a case wherein you need to maintain a mapping between a Class<?> instance and the list of all methods it holds. Given that the JVM is perfectly capable of dynamic class loading and unloading, it's quite possible that the class you have in your map as a key is no longer needed (doesn't have anything else pointing to it). Now, if you would have used a "strong" reference to maintain the class to method mapping, your class will stick around as long as your map is reachable which isn't a good position to be in this case. What you would really want is that once there are no live references to your "class", it should be let go by the map. This is exactly what a weak hash map is used for.

EDIT: I would recommend giving this thread a read.

Community
  • 1
  • 1
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71