Possible Duplicate:
synchronized block vs synchronized method?
From accepted answer to this question: In Java critical sections, what should I synchronize on?
I learn that
public synchronized void foo() {
// do something thread-safe
}
and:
public void foo() {
synchronized (this) {
// do something thread-safe
}
}
do exactly the same thing. But in first case we make synchronized only one method of object, and in second case we make inaccessible Whole object. So why this two code snippests do same things?
You seem to be mixing things.
Firstly
is equivalent, from a synchronization perspective, to:
The pros / cons have already been mentioned and the various duplicates give more information.
Secondly,
means that the instructions in the synchronized block can’t be executed simultaneously by 2 threads because they need to acquire the monitor on
someObjectto do so. (That assumes that someObject is a final reference that does not change).In your case,
someObjecthappens to bethis.Any code in your object that is not synchronized, can still be executed concurrently, even if the monitor on
thisis held by a thread because it is running the synchronized block. In other words,synchronized(this)does NOT “lock the whole object”. It only prevents 2 threads from executing the synchronized block at the same time.Finally, if you have two
synchronizedmethods (both usingthisas a lock), if one thread (T1) acquires a lock onthisto execute one of those 2 methods, no other thread is allowed to execute any of the two methods, because they would need to acquire the lock onthis, which is already held by T1.That situation can create contention in critical sections, in which case a more fine grained locking strategy must be used (for example, using multiple locks).