The difference between synchronized(this)
and synchronized(m)
is that by synchronizing on this
, you synchronize on the entire instance. So, as you would expect, no body would be able to synchronize on this
while you hold the lock.
public synchronized void foo() {
// Handle shared resource
}
is similar to
public void foo() {
synchronize(this) {
// Handle shared resource
}
}
By using objects, such as m
, you get a more fine grained control over what you want to synchronize and when. But remember that if someone uses foo(), as shown above, it will not stop access to methods that are not synchronized on this
:
public void anotherLock() {
synchronized(m) {
// Should handle another shared resource
// otherwise you might get unexpected results
}
}
While a thread is using foo()
, another thread can access anotherLock()
.