Search code examples
javascaladictionaryweak-references

ConditionalWeakTable/weak dictionary in Java or Scala


In .NET, there is a class called ConditionalWeakTable. This is a map/dictionary that makes some guarantees about object lifetime and eligibility for garbage collection.

It holds weak references to keys, and automatically removes keys if they cannot be reached from anywhere outside the table (so keys aren't persisted by being members of the table, nor are they persisted if they can be reached from any other similarly unreachable key or value in the table, even if there are circular references and the like).

Values are still kept alive by the table, but they are removed if the key is removed because it is unreachable.

This class is used to attach properties to objects at runtime without causing memory leaks or interfering with garbage collection.

Is there a way to duplicate this kind of functionality in Java or Scala?


Solution

  • You can either use Java's WeakHashMap<K,V>:

    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.

    Or if you're using Scala, use the wrapper provided by scala.collection.mutable.WeakHashMap[A,B]