Wednesday, August 06, 2008

Lock on value types again

While doing some code analysis I came across the following chunk of code. If you can, try to figure out the problem.
private static bool _blnCrap = true;

public static void CrapFunction()
{
lock((object) _blnCrap)
{
//Some more shit
}
}
The problem above is the lock isnt effective at all. The first thread comes, casts the bool variable to an object. Now when you cast a value type to a reference type boxing happens, a new object is created on the heap. Now the lock will be placed on this new object. When the first thread is still inside the lock, a second thread comes and tries to obtain a lock on (object) _blnCrap. Again when you say (object) _blnCrap, boxing will happen and a new object will be created on the heap. This object is different from the object created by the first thread and so the thread will be able to obtain a lock and go inside.

Locks cannot be placed on value types. If the explicit cast isnt placed compiler will show an error: <Type> is not a reference type as required by the lock statement.
Why? Go through my earlier post below
Synchronising access against value types

No comments: