In java we have WeakHashMap builtin data structure. I have read documents about it. I would like to what are the practical use cases for weakhashmap .?
Asked
Active
Viewed 188 times
1 Answers
1
The usual use case is storing information related to an object separately from the object itself, without locking the object in memory. There are a couple of reasons you'd want to do that:
- Branding objects in a way that can't be faked (e.g., "have I see this object before, or is it just a perfect copy of an object I've seen before?")
- Storing truly-private information about an object (remember that
private
fields can be accessed via reflection)
Rough, conceptual example:
class Example {
private static WeakHashMap<Example, Data> details = new WeakHashMap<>();
private static class Data {
// ...private information...
}
public Example() {
Data d = new Data();
details.set(this, d);
}
public void doSomething() {
Data d = details.get(this);
if (d == null) {
throw new IllegalStateException();
}
// ...do something...
}
}
Since the keys are held weakly, the objects can still be garbage-collected if the caller releases their reference, even though the object is used as a key in the map.
It's probably worth noting that you'd want to at least obscure the above behind an interface or something, since...private fields can be accessed via reflection, and so it's possible to get details
from Example
and then use the object reference to get the Data
object from it. Raises the bar a bit. :-)

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
-
nice explanation . thank you so much T.J. Crowder ... worth knowing ... might be limited use in when develop apps :) – Globe Admin Dec 04 '18 at 09:00