Friday, November 18, 2005

Synchronizing static methods in Java threads

While teaching Java threads, a student asked me a very interesting question: When a thread calls a synchronized method of an object, it obtains the lock of the object, however how can a thread call a synchronized method that is static? An object may not even have been created when the static method is called.

To understand this better, let us look at a simple example of a class which contains two synchronized method: one static and one non-static.

public class SynchedClass {
public synchronized aMethod() {}
public static synchronized bMethod() {}

When a thread calls SynchedClass.bMethod(), it obtains a lock on the class java.lang.Class that represents the SynchedClass. Whenever the JVM loads a class it creates an instance of java.lang.Class which represents all objects of the loaded class. An instance of the class Class is created even before any object of that class is instantiated. When a synchronized static method is invoked the invoking thread obtains a lock to the class Class.
Note that if a thread calls a non-static synchronized method and obtains it's lock, another thread could concurrently call a static synchronized method of the same object, because they are locked on different objects.

No comments: