Obtains lock of 'this' object, which is clear. But, if the thread obtains the lock of 'obj', how lock of object on which this method is called is obtained?
In other words, what is the difference?
The difference is that in the first example, the lock of the object that the method is called on is used (because that's the object that this refers to), and in the second example, the lock of the object that the variable obj refers to is used.
then, if I'm calling a method inside synchronized block, while the thread is inside that method, other thread also can call same method on same instance of class A as lock of that instance is not obtained in case2.
Correct me if I'm wrong.
Jayavardhan geepi wrote:In other words, what is the difference?
I think Jesper covered most of it; however, a concrete example might be a case where you want to keep "reads" and "writes" separate. If you just synchronize on 'this', the two types of method would be competing for the same lock when they don't need to, so an alternative might be:Do you see what's happened? The code is still synchronized, so only one read or write can occur at a time, but the methods don't interfere with each other so a read can take place while a write is happening (not sure you'd actually want to do that, but it's just for illustration).
You may also want to look at ReentrantLock: a very useful new addition to the concurrent package.
Isn't it funny how there's always time and money enough to do it WRONG?
Joined: Jul 21, 2010
Am I right here?..
I have, and I'm doing from inside 1st synchronized block of above example by Winston.
So, only someRead method is synchronized irrespective of on which instance it is called.
i.e even subsequent code has to wait until first call to someRead() is finished?
Jayavardhan geepi wrote:read1.someRead();[/code] from inside 1st synchronized block of above example by Winston.
No, synchronization works from outside, and you don't have any in the example you showed.
Basically, a synchronized block can only be run by one Thread at a time; however, what you synchronize on determines whether (or when) the Thread is blocked or not. A synchronized method always synchronizes on this, so if you don't want to block all other synchronized methods for the object, you need to find some other way of doing it. The example I gave you above is just one (and it is just an example; I wouldn't expect anyone to code it that way).
And make sure you understand that syncing only stops other threads from entering other synced blocks or methods on the same lock. It has no effect on another thread calling an unsynchronized method or executing code that's not in a synchronized block.