My take would be there is no difference between the two, except that the synch block might be more localized in scope and hence the lock will be of lesser time ??
Yes. You are right. Unlike synchronized
methods, synchronized statements must specify the object that provides the intrinsic lock.
Example from java tutorial:
public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}
Synchronized statements are also useful for improving concurrency with fine-grained synchronization. You can find good example on same tutorial page for below use case.
Suppose, for example, class MsLunch
has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized
, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.
And in case of Lock on a static method, on what is the Lock taken ? What is the meaning of a Lock on Class ?
In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.
When you make a method as synchronized ( non static
) :
It is not possible for two invocations of synchronized
methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
If you make a method as static synchronized
:
It is not possible for two invocations of static synchronized
methods on different objects of same class to interleave. When one thread is executing a static synchronized
method for an object of Class A, all other threads that invoke static synchronized
methods on any of objects of Class A block (suspend execution) until the first thread is done with the method execution.
You find better alternatives to synchronization in this SE question:
Avoid synchronized(this) in Java?