Java.Multithreading.On which object does synchronization occur when calling a static synchronized method?

When you declare a static synchronized method in Java, synchronization happens on the Class object, not on an instance of the class.

🧠 Why?

Because a static method doesn’t belong to any instance — it belongs to the class itself. So when you use synchronized on it, Java locks the Class<?> object representing that class.

✅ Example

public class MyClass {
    public static synchronized void staticMethod() {
        // synchronized on MyClass.class
        System.out.println("Static synchronized method");
    }

    public synchronized void instanceMethod() {
        // synchronized on 'this' (the object instance)
        System.out.println("Instance synchronized method");
    }
}
  • staticMethod() → synchronized on MyClass.class
  • instanceMethod() → synchronized on this (the object instance)

🔍 Confirm It with This Code:

public class SyncTest {
    public static synchronized void staticSyncMethod() {
        System.out.println(Thread.currentThread().getName() + " entered staticSyncMethod");
        try { Thread.sleep(2000); } catch (InterruptedException e) {}
        System.out.println(Thread.currentThread().getName() + " leaving staticSyncMethod");
    }

    public static void main(String[] args) {
        Runnable r = () -> SyncTest.staticSyncMethod();

        Thread t1 = new Thread(r, "Thread-1");
        Thread t2 = new Thread(r, "Thread-2");

        t1.start();
        t2.start();
    }
}

📌 Output:

Thread-1 entered staticSyncMethod
Thread-1 leaving staticSyncMethod
Thread-2 entered staticSyncMethod
Thread-2 leaving staticSyncMethod

This shows that Thread-2 waits until Thread-1 finishes — they’re locking on the same object: SyncTest.class.

🔒 Technically:

synchronized static void method() { ... }

Is equivalent to:

static void method() {
    synchronized (MyClass.class) {
        ...
    }
}
This entry was posted in Без рубрики. Bookmark the permalink.