Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Detailed Answer: Your own ThreadLocal

DZone's Guide to

Detailed Answer: Your own ThreadLocal

·
Free Resource

In the last post, we have shown this code:

public class CloseableThreadLocal
{
[ThreadStatic]
public static Dictionary<object, object> slots;

private readonly object holder = new object();
private Dictionary<object, object> capturedSlots;

private Dictionary<object, object> Slots
{
get
{
if (slots == null)
slots = new Dictionary<object, object>();
capturedSlots = slots;
return slots;
}
}


public /*protected internal*/ virtual Object InitialValue()
{
return null;
}

public virtual Object Get()
{
object val;

lock (Slots)
{
if (Slots.TryGetValue(holder, out val))
{
return val;
}
}
val = InitialValue();
Set(val);
return val;
}

public virtual void Set(object val)
{
lock (Slots)
{
Slots[holder] = val;
}
}

public virtual void Close()
{
GC.SuppressFinalize(this);
if (capturedSlots != null)
capturedSlots.Remove(this);
}

~CloseableThreadLocal()
{
if (capturedSlots == null)
return;
lock (capturedSlots)
capturedSlots.Remove(holder);
}
}

And then I asked whatever there are additional things that you may want to do here.

The obvious one is to thing about locking. For one thing, we have now introduced locking for everything. Would that be expensive?

The answer is that probably not. We can expect to have very little contention here, most of the operations are always going to be on the same thread, after all.

I would probably just change this to be a ConcurrentDictionary, though, and remove all explicit locking. And with that, we need to think whatever it would make sense to make this a static variable, rather than a thread static variable.

Topics:

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}