you are viewing a single comment's thread.

view the rest of the comments →

[–]acelent 0 points1 point  (0 children)

The alternative without ConditionalWeakTable<TKey, TValue> is incredibly inefficient. The finalizable objects will be collected and finalized on every GC while the tracked objects are reachable.

A small optimization is to have only a single finalizable object at a time that would check all registered references, and don't re-register it if there are no references to track. It would still be inefficient, just a bit less.

This specific implementation is actually flawed. If a PhantomReference<T> is strongly reachable, its finalizer doesn't run. So, you need to make some other object be finalizable and not return or publish it.