Threading. Singletons. Generics. Locking Bug!

I recently came across this very interesting bug.  Note: the problem requires understanding of threads, generics, inheritance and locks.

In particular look at the Locking Bug code. Specifically, notice how the locking behaviour changes based on the types used for the generic base class.

  • When the types are same, the base class object used for locking is the same.
    • So locking can be enforced by doing something like
      • private static readonly object Padlock = new object();
      • lock (Padlock)
  • However, when the types are different, the compiler creates two completely different memory objects, hence the locking does not come into play
    • A possible solution is to create a separate internal class and enforce locking using the typeof that class
      • internal class ForLocking {}
      • lock (typeof(ForLocking))
    • If you dont prefer using typeof, another option is to create a separate class and have a static lockObject in it.
      • See code.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s