Search code examples
javadictionarygarbage-collectionjava-8weak-references

Weak association of one object with another in Java?


When I have come class

class MyClass1 {
    MyClass2 member;
}

ans it is garbage collected, then member also become eligible to garbage collection.

Can I simulate the same relation with Map?

So, I wish a map with weak references to keys. I.e. map itself should not prevent keys from garbage collection. And once key is garbage collected, then its associated value also become eligible to garbage collection.

Is this possible?

UPDATE

Is this just WeakHashMap?


Solution

  • Absolutely. Just use a WeakHashMap, which will use weak references to keys and remove entries when keys are garbage collected.