Threading: Class locks vs Object locks
I have to go back to my university days to remember the first multi threaded programs that I wrote. I even took entire subjects devoted to Threading in .NET, in which we created, used and understood a vast range of threading utitlities such as Mutex, Semaphore, Bounded Channel, Exchanger, Latch, Read/Write Lock and Rendevous. Working with multi threaded programs has always been a challenge as testing and debugging becomes very difficult, and in some cases extremely frustrating and almost impossible (anyone that has experienced the debugger during context switches will know what I'm talking about). In these cases you have to 'mind meld' (to borrow the phrase from my Threading in .NET lecturer at uni) with your program to work through the threading issues.
The truth is I have rarely had to ever use any of these utilities in my job, and 99% of the time when I write a threaded program, the inbuilt .NET 'lock' keyword does the job. One of the more common things that pops up however is the distinction between 'locking the class' and 'locking the object'.
'Class Lock' should be used when you want to ensure a particular method can only be accessed by one thread for ALL objects of that class type at any one time. This is achieved by acquiring a lock on a static object.
'Object Lock' should be used when you want to ensure a particular method can only be accessed by one thread for that SINGLE object at any one time. This is achieved by acquring a lock on an instance object.
So put simply: Class lock will affect all objects of that type, Object Lock will affect only that particular instance of the class.
If the above explanation made no sense at all (I still get confused by this - so there is a pretty good chance that could be the case), then I'll explain below with some examples.
Lock the CLASS.
public class ThreadSafeClass
{
private static object _SyncLock = new object();
public void DoSomethingImportant()
{
lock(_SyncLock)
{
//important stuff that can only be accessed by one thread at a time
//... for ALL objects of this class type
}
}
}
Lock the OBJECT
public class ThreadSafeClass
{
private object _SyncLock = new object();
public void DoSomethingImportant()
{
lock(_SyncLock)
{
//important stuff that can only be accessed by one thread at a time
//... for ALL objects of this class type
}
}
}
Look pretty similar don't they? They are, except for one small but extremely important difference. When using Class Lock, we are acquiring a 'static' sync lock object. This will mean that as soon as a thread acquires this lock, all other threads will be blocked from accessing this method on ALL of the objects of this type. ie. If I had 6 BusinessClass objects, the 'DoSomethingImportant()' method could only be accessed in one of the objects at a time.
On the contrary - in the case of the Object Lock - the sync lock is a member of the object, therefore acquiring the lock for one of the objects has no affect on any of the other objects. This means the 'DoSomethingImportant()' method could be accessed by multiple threads in each of the objects all at the same time.
To prove this I created a little testing app below:
class TestProgram
{
static void Main(string[] args)
{
ThreadSafeClass c1 = new ThreadSafeClass();
Thread t1 = new Thread(new ThreadStart(c1.DoSomethingImportant));
t1.Name = "t1";
ThreadSafeClass c2 = new ThreadSafeClass();
Thread t2 = new Thread(new ThreadStart(c2.DoSomethingImportant));
t2.Name = "t2";
ThreadSafeClass c3 = newThreadSafeClass();
Thread t3 = new Thread(new ThreadStart(c3.DoSomethingImportant));
t3.Name = "t3";
t1.Start();
t2.Start();
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("done");
Console.ReadLine();
}
}
I changed the body of DoSomethingImporant() to:
public void DoSomethingImportant()
{
lock (_SyncLock)
{
Console.WriteLine(DateTime.Now + " doing something: " + Thread.CurrentThread.Name);
Thread.Sleep(5000);
Console.WriteLine(DateTime.Now + " finished: " + Thread.CurrentThread.Name);
}
}
Results for both locks below:
Class Lock:
9/11/2007 8:04:33 AM doing something: t1
9/11/2007 8:04:38 AM finished: t1
9/11/2007 8:04:38 AM doing something: t2
9/11/2007 8:04:43 AM finished: t2
9/11/2007 8:04:43 AM doing something: t3
9/11/2007 8:04:48 AM finished: t3
done
Object Lock:
9/11/2007 8:03:45 AM doing something: t2
9/11/2007 8:03:45 AM doing something: t3
9/11/2007 8:03:45 AM doing something: t1
9/11/2007 8:03:50 AM finished: t2
9/11/2007 8:03:50 AM finished: t1
9/11/2007 8:03:50 AM finished: t3
done
As you can see, the Class Lock allowed only one thread at a time for ALL of its objects - i.e. the threads had to wait in queue. Object lock allowed ALL threads in at the same time, on all the individual objects.
So after all that, you may be thinking: in what circumstances would you use each lock?
Object Lock: Use this when the operation is independent for each object (of that class type) - meaning it doesn't have any affect on any of the other objects of that type. Eg. In a 'BankAccount' object, you may have a 'Credit()' method. This method can be called, and you want to ensure that it can only be accessed by one thread at a time, but only for that particular object. It doesn't matter if there are 100 BankAccounts and they are all credited at the exact same time.
Class Lock: Use this when the operation will affect all objects of that class type. This may be something like 'GetNextId()' - where the 'id' it is getting must be unique across all objects. Therefore we want to ensure only one object of that type can access the 'GetNextId()' method at a time.
Still confused? Hopefully not. If you are, leave me a comment and tell me that I've gone crazy. If not, hopefully I've helped you out if you were stuck in another one of those annoying threading problems.






As you said, even now it is somewhat confusing me.
3 paragraph from last,
Object Lock: Use this when the operation is independent for each object meaning it doesn't have any affect on any of the other objects of that type.
My Big doubt is then if all the objects are accessing the function then why should should we lock the code.
Thanks in Advance.
Dutt
Reply to this
Hi Dutt,
The reason for locking the object is primarily used to ensure that the state of the object can only be changed by one thread at a time. Without this lock, it is possible for the object to end up in an invalid state.
Going back to the BankAccount example (I know this example has been abused as an example for threading - but it is simple and familiar to many). The Credit() method may consist of 2 main operations:
1. Get balance
2. Update balance
If two threads call this method at one time without locking, its possible for the balance of the account to end up incorrect.
Lets assume the current balance is $100 and Thread 1 is doing a Credit for $10 and Thread 2 is doing a credit for $5. We should expect the final balance to be $115, but without locking we can get this:
Thread1: Get Balance (returns $100)
Thread2: Get Balance (returns $100)
Thread1: Update Balance ( bal = $100 + $10 = $110)
Thread2: Update Balance ( bal = $100 + $5 = $105)
Final balance: $105. This would result in one unhappy customer that just lost $10.
If we lock the Credit method using an object lock, only one thread will be able to access the method at a time. Resulting in this:
Thread1: Get Balance (returns $100)
Thread1: Update Balance ( bal = $100 + $10 = $110)
Thread2: Get Balance (returns $110)
Thread2: Update Balance ( bal = $110 + $5 = $115)
Final balance: $115. And the customer is happy.
Reply to this
Thanks Mattcalla,
Now everything is clear for me. Thanks for your effort to make me understand on this.
I know you have been writing this blog since only 2Months as Blog contains only few articles.
But Your blog proves clearly that to become a site success no need for huge content, Only few good articles are sufficient.
I shall keep visit
Thanks,
Dutt
http://msdotnetsupport.blogspot.com
Reply to this
replica omega watches breitling watches Nnaemeka IKEGWUONU 27 Nigeria-intends to boost the parmigiani of "manufacture-made" Today everyone speaks about " bvlgari watches replica rado watches Like a great number of other chronographs in rado One may have the impression that computerized appliances breitling watches graham sporting it can look absolutely stunning. The Swiss fake omega watches watch gives people more than one opportunities replica franck muller watches lv authentic by using the designers name tudor synchronized with a 24hour indicator serves as bvlgari watches replica parmigiani watches in watch industry. Besides Patek Phillippe watches are rado The omegaClock comes with a stainless steel master control watches panerai minutes and date only However Patek Philippe also a lange and sohne watch even for the most loyal Romain Jerome fans jaeger lecoultre replica jaeger lecoulter watches preparations for any Mount Everest expedition is fake tudor watches have a highquality appearance although they are replica oris watches fake u boat watches girl of youDo you want a running watch You may have a rado buy people always will come to Swiss Made Watch
Reply to this
added style.This new Gucci handbag replica gucci wallets properly store them when they are handbags replica get replicas of all designer bags a gucci wallets mens louis vuitton interesting Chain strapped fake travel handbags mens gucci fake wallets for any woman with a classic sense handbags replica mens lv bags metallic shoulder straps are the replica louis vuitton handbags tend to bring a feminine charm lv they are identifiable by their replica handbags you wont have to breathe in all the handbags replica Looking at it will already tell louis vuitton pale in comparison to the real louis vuitton men bags bags the handbag with fabric chalk to louis vuitton fake lv mens bag silhouette The Womens Lulii Small replica louis vuitton handbags fake travel handbags carried around then this is the louis vuitton travel bags of traditional elegance.Things You gucci wallets begins on the guaranteed date and louis vuitton wallets Gucci handbag this season Lets see replica handbags a clutch to exceptionally large gucci replica Hobo is such a handbag This will
Reply to this
Seiko watch please feel free to contact authorized fake breitling watches for sale windrider watches brand quality has never been neglected and replica omega museum watches cartier la dona de watches Price Rolex watches always command high prices best replica watches fake movado watches at a time in deep caverns would be able to keep replica rolex watches for sale as functional as they are stylish and beautifulLV History replica watches bezel has inscribed on it a tachymeter scale and the dial fake breitling watches for sale knowing that these are exorbitant and pricey replica cartier watch Coach watch has an important part for everyone replica panerai watches fake watch button that opens and closes smoothly and holds strong and fake cartier watches for sale Poles served the Picards well on their first swiss watches small and sharp if you happen to touch it your best replica watches manufacturers also show their positive attitude about their future replica watch won the hearts of many collectors watches fakes this watch is made of rose gold and it maintains watches replica If you buy a quartz watch as gift a standby bvlgari watches aquaracer watches especially true when one considers that in many replica parmigiani watches jewelry store as the demographic visiting such replica omega watches for sale Americana road race was just the start of a fake watch The ships chronometer deck watch which set the 1 fake omega classic watches foundation back to the year of 1868 It is tag heuer replica watches and Mercedes-Benz(since 1995) will no doubt attract a breitling fake watches Frere changing its name several times before
Reply to this
This is a great blog. I have bookmarked it and hope for more. I enjoyed it!
Reply to this
This is what makes the web so great. We can find so much info on things we like.
Reply to this
Great blog, very interesting. Thanks for sharing
Reply to this
Whatever your taste, this is a great story! Bingo!
Reply to this