Steven Levine
Steven Levine
~1 min read

Tags

What happens when you try to synchronize on a static method? When a static synchronized method is called, which object are we referring to? A static method does not have a notion of a this reference. It is not possible to obtain a lock on an object that does not exist.

How does it work? When a static synchronized method is called a Class lock is obtained before calling the method. This mechanism is exactly the same as the non-static implementation. It just obtains a different lock. The same exact synchronization rules apply to a class lock that apply to an object lock.

How is this lock related to the object lock? They are not related at all. In ?F fact, they can be used independenly of each other. If a non-static synchronized method calls a static synchronized method, they are effectivly obtaining both a class lock and an ojbect lock. Achieving a deadlock between these two locks is difficult, but not impossible since a static synchornized method can only call a non-static synchronized method via an ojbect reference.