Back in the PDC build of .NET 4.0 another interesting new feature was introduced: ConditionalWeakTable<TKey, TValue>. This is a special purpose dictionary to associate objects with other objects. It was introduced to help the DLR, which needs the ability to add properties to arbitrary objects. The documentation is pretty clear and the CLR team blog also has some info on it, so I won't rehash that. Instead I'll just mention that ConditionalWeakTable itself is not a magic type (i.e. the runtime knows nothing about it), but instead it is built on top of a private value type System.Runtime.Compiler.Services.DependentHandle. DependentHandle is essentially a handle based ephemeron implementation.
JVM vs CLR
This means that the CLR now comes a bit closer to the JVM in terms of memory management features. The JVM has had some very interesting reference types for a long time (WeakReference, SoftReference and PhantomReference) and the ability to have these references posted to a ReferenceQueue by the GC when the relevant change in reachability to the referenced object occurs.
Unfortunately there still isn't parity between the CLR and JVM, even though the CLR now provides a capability the JVM doesn't.
||.NET has no ReferenceQueue equivalent notification mechanism.|
(If you think that Java's WeakHashMap and .NET's ConditionalWeakTable are similar, consider that ConditionalWeakTable is ephemeron based. Plus the fact that WeakHashMap uses short weak references and ConditionalWeakTable uses long weak references.)
ConditionalWeakTable is very useful for IKVM in several places:
- Used to support class unloading by mapping Assembly to ClassLoader.
- Used in caching of MethodBase properties.
- Can be used to track the type of ghost arrays.
- Can be used to more efficiently implement adding references to a ReferenceQueue.
Given the effort going into Java 7 to improve support for dynamic languages it would not be surprising nor unwelcome to see ephemerons being added to the JVM.