difference between synchronizing a static method and a non static method

Viewed 40638

What is the difference between synchronizing a static method and a non static method in java?Can anybody please explain with an example. Also is there any difference in synchronizing a method and synchronizing a block of code?

7 Answers

From javadoc https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

when a static synchronized method is invoked, since a static method is associated with a class, not an object. 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.

public static synchronized void getInstance(){}

When we acquire a lock on any class, we actually acquire a lock on "Class" class instance which is only one for all instances of class.

public synchronized void getInstance(){}

we can create multiple object's of a class and each object will have one lock associated with it.

Related