ConditionalWeakTable/weak Java 或 Scala 中的字典

ConditionalWeakTable/weak dictionary in Java or Scala

在 .NET 中,有一个名为 ConditionalWeakTable 的 class。这是一个map/dictionary,它对对象生命周期和垃圾收集的资格做出了一些保证。

它持有对密钥的弱引用,如果无法从 table 之外的任何地方访问密钥,它会自动删除密钥(因此密钥不会因为成为 table 的成员而持久化,也不会如果可以从 table 中任何其他类似的无法访问的键或值访问它们,它们就会持续存在,即使存在循环引用等)。

值仍然由 table 保持活动状态,但如果因为无法访问键而被删除,它们也会被删除。

此 class 用于在运行时将属性附加到对象,而不会导致内存泄漏或干扰垃圾回收。

有没有办法在 Java 或 Scala 中复制这种功能?

您可以使用 Java 的 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.

或者,如果您使用的是 Scala,请使用 scala.collection.mutable.WeakHashMap[A,B]

提供的包装器