Ayende @ Rahien

It's a girl

An elegant ThreadLocal for Silverlight

One of the annoying bits about Silverlight is how much of what I consider core API isn’t there. For example, concurrent collections or thread local.

I didn’t have the time to implement concurrent collections properly, but thread local isn’t really that hard. Here is a simple implementation:

public class ThreadLocal<T>
{
    private readonly Func<T> valueCreator;

    public class Holder
     {
         public T Val;
     }

    [ThreadStatic]
    private static ConditionalWeakTable<object, Holder> _state;

    public ThreadLocal():this(() => default(T))
    {
    }

    public ThreadLocal(Func<T> valueCreator)
    {
        this.valueCreator = valueCreator;
    }

    public T Value
    {
        get
        {
            Holder value;
            if (_state == null || _state.TryGetValue(this, out value) == false)
            {
                var val = valueCreator();
                Value = val;
                return val;
            }
            return value.Val;
        }
        set
        {
            if (_state == null)
                _state = new ConditionalWeakTable<object, Holder>();
            var holder = _state.GetOrCreateValue(this);
            holder.Val = value;
        }
    }
}

The fun part, it satisfies the entire contract, but I am willing to bet it is going to cause some head scratching.

Comments

configurator
04/28/2011 09:44 AM by
configurator

Why do you need the ConditionalWeakTable here though?

Ayende Rahien
04/28/2011 09:45 AM by
Ayende Rahien

Configurator,

Try putting anything else in its place

Patrick Huizinga
04/28/2011 09:47 AM by
Patrick Huizinga

@configurator

Because when a ThreadLocal instance is GCed, you want the value to be cleaned up with it. And since garbage collection is likely on a separate thread, you can't use the finalizer.

configurator
04/28/2011 09:48 AM by
configurator

What's wrong with private static Holder _state; ?

Ayende Rahien
04/28/2011 09:49 AM by
Ayende Rahien

Configurator,

a) it won't be thread static?

b) it won't ever get cleaned up?

configurator
04/28/2011 09:49 AM by
configurator

D'oh, I forgot that this is static... Been using ThreadLocal for too long!

Duarte Nunes
04/28/2011 10:16 AM by
Duarte Nunes

There's a disadvantage: if you have N threads using the ThreadLocal instance, and N-1 thread exit, then the values that they created will only be GCed when the Nth thread exits.

Since ConditionalWeakTable is already thread-safe, I would have:

private ConditionalWeakTable <thread,> _state;

and index with Thread.CurrentThread.

Duarte Nunes
04/28/2011 10:22 AM by
Duarte Nunes

Hm, let me try again: it's ConditionalWeakTable<Thread, Holder>.

Duarte Nunes
04/28/2011 10:33 AM by
Duarte Nunes

Oops, the ConditionalWeakTable is ThreadStatic. Nevermind my earlier post.

Simone
04/28/2011 09:16 PM by
Simone

Hi Oren, very nice solution. I think this might be an excellent TDD excercise, do you have any tests that cover your implementation you can share to create a sort of kata on top of them?

Jon Wingfield
04/30/2011 12:02 AM by
Jon Wingfield

I don't get why you're not using a weak reference instead of the table. Not in silverlight either?

Simone
04/30/2011 01:08 AM by
Simone

@Jon, I'd guess because you want the lifecycle of the Value to be tied to that of the TL instance, thus GCed when the TL instance is GCed but not earlier.

Jay R. Wren
05/22/2011 04:30 PM by
Jay R. Wren

My only thought was "be glad you have ConditionalWeakTable" I'd hate (or I'd like to see it, but I'd hate the added complexity) to see how you would have to do this in SL3 without CWT

Comments have been closed on this topic.