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
    }
}

Print | posted on Thursday, October 09, 2008 1:21 AM

Feedback


Gravatar

# re: Safe for multi threading... 10/9/2008 3:43 AM Judah Himango

Heheh, nice!


Gravatar

# re: Safe for multi threading... 10/9/2008 5:40 AM 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 field;
// ...
}

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


Gravatar

# re: Safe for multi threading... 10/9/2008 5:43 AM 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.


Gravatar

# re: Safe for multi threading... 10/9/2008 6:28 PM 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?


Gravatar

# re: Safe for multi threading... 10/10/2008 5:17 AM Jacob Stanley

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

Title  
Name  
Email
Url
Comments   
Please add 5 and 1 and type the answer here: