| Author |
difference between synchronized (SomeClass.class) {} and synchronized (objOfSomeClass) {}
|
ilias basha
Ranch Hand
Joined: Nov 27, 2008
Posts: 55
|
|
I have noticed sometimes in code having
and also in conventional style
Is there any difference between these two lines[assuming 'this' object refers the current object of SomeClass in my example].
|
 |
Chris Hurst
Ranch Hand
Joined: Oct 26, 2003
Posts: 370
|
|
If it helps try to think of it this way (not quite true) the object SomeClass.class is like the plans/ manual for SomeClass objects , 'this' in your case is an instance of SomeClass , there strongly related but completely different. The car manual and the car aren't the same thing though there both objects and can therefore be synchronized on.
The first is as per a static method the second non static object method, the first gives you a way of synchronizing across all instances of a class the second gives you a way of synchronizing on one particular instance.
Hope that helps, its a tricky and confusing subject, another way to look at it is run the code in the debugger and have a peek at those objects your synchronizing on or read this class documentation
|
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
|
 |
ilias basha
Ranch Hand
Joined: Nov 27, 2008
Posts: 55
|
|
Chris Hurst wrote:the first gives you a way of synchronizing across all instances of a class the second gives you a way of synchronizing on one particular instance.
The above line left me with more confusion, than what i had earlier
How is it possible to all instances can be at synchronized block, though your second point is pretty understandable.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3053
|
|
Let's say you have two different instances of the same class, who need to update some static field when they do work. In this case, you will have to use the class to synchronize on, because the static field is shared between instances:
In this code, n keeps track of how often doStuff is called, no matter on which instance it is called on. In order to update n, you need to make sure that no other thread accesses it at the same time. Because n is shared between different instances, you can't use synchronized(this), you have to use a lock that is also shared between different instances. In this case, we use Example.class, which we can be quite certain will be shared between all instances of Example.
Note that it doesn't matter what lock you use to synchronize on, as long as it is the same lock for all instances. We could also have used Object.class (which is also visible to all instances of Example) or even String.class or some static Object field in Example:
Note that using the current class (Example.class in this case) is just the standard way of doing things.
|
 |
 |
|
|
subject: difference between synchronized (SomeClass.class) {} and synchronized (objOfSomeClass) {}
|
|
|