Ayende @ Rahien

Unnatural acts on source code

Safe for multi threading...

The easiest way of getting there is to have no mutable state. And here is a simple test to ensure that. Seeing how CouchDB code works and how erlag handle things is quite educating in this regard.

[TestFixture]
public class EnssureTypesSafeForMultiThreadingTestFixture
{
    [Test]
    public void TypeIsSafeForMultiThreading()
    {
        var visitedTypes = new List<Type>
        {   // immutable types, partial list
            typeof(int),
            typeof(long),
            typeof(string),
            typeof(DateTime)
        };
        foreach (var type in GetRootTypesToCheck())
        {
            CheckType(type, visitedTypes);
        }
    }

    private static void CheckType(Type type, ICollection<Type> types)
    {
        if(types.Contains(type))
            return;
        types.Add(type);
        var fields = type.GetFields(BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public);
        foreach (var info in fields)
        {
            var isReadOnlyField = (info.Attributes & FieldAttributes.InitOnly)==FieldAttributes.InitOnly;
            if(isReadOnlyField==false)
                throw new InvalidAsynchronousStateException("Dude, " + type + "." + info.Name +
                                                            " is not marked as read only. You are NOT safe for multi threading, enjoy the deadlock, bye!");
            CheckType(info.FieldType, types);
        }
    }

    private static IEnumerable<Type> GetRootTypesToCheck()
    {
        // return types that I am interested in verifying
    }
}

Comments

Jacob Stanley
10/09/2008 03:40 AM by
Jacob Stanley

It would also be cool to check if the type of the field was immutable. Otherwise the following would be verified as thread safe, when it's not:

class MyClass

{

private readonly List <int field;

// ...

}

I remember reading a blog article with some good ideas about verifying immutability - blogs.msdn.com/.../...ng-immutability-in-code.aspx>.

Jacob Stanley
10/09/2008 03:43 AM by
Jacob Stanley

Ahh ok, you are doing that, it's just that it depends on the ordering of types in the GetRootTypesToCheck() collection as to whether it works or not.

configurator
10/09/2008 04:28 PM by
configurator

@Jacob, How does the ordering matter? Am I missing something here? It seems that the recursive call would check the inner type for immutability whether it has been checked or not, wouldn't it?

Jacob Stanley
10/10/2008 03:17 AM by
Jacob Stanley

So it would, wow I must've having been having a bad day yesterday!

Comments have been closed on this topic.