Wrong Answer #3: Your own Thread Local
Join the DZone community and get the full member experience.Join For Free
Last time, we forgot that the slots dictionary is a thread static variable, and that the finalizer is going to run on another thread… Let us fix this, too:
public class CloseableThreadLocal
public static Dictionary<object, object> slots;
private readonly object holder = new object();
private Dictionary<object, object> capturedSlots;
private Dictionary<object, object> Slots
if (slots == null)
slots = new Dictionary<object, object>();
capturedSlots = slots;
public /*protected internal*/ virtual Object InitialValue()
public virtual Object Get()
if (Slots.TryGetValue(holder, out val))
val = InitialValue();
public virtual void Set(object val)
Slots[holder] = val;
public virtual void Close()
if (capturedSlots != null)
if (capturedSlots == null)
And now it works!
Except… Under some very rare scenarios, it will not do so.
What are those scenarios? Why do we care? And how do we fix this?
Dictionary (software) Finalizer
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
A Comprehensive Guide To Testing and Debugging AWS Lambda Functions
How To Use an Automatic Sequence Diagram Generator