synchronized static Methods
What You'll Learn: You'll learn how synchronized on a static method locks the entire Class object, coordinating access across all instances of the class.
The Core Idea
When you declare a static method as synchronized, you're no longer locking on individual object instances—you're locking on the Class object itself. This means only one thread can execute any synchronized static method of that class at a time, regardless of how many instances exist.
Think of it this way: synchronized instance methods are like securing individual hotel rooms (each object has its own lock). Synchronized static methods are like securing the hotel's main conference room—there's only one, shared by everyone.
How It Works
public class SharedCounter {
private static int count = 0;
public static synchronized void increment() {
count++;
}
public static synchronized int getCount() {
return count;
}
}
When Thread-A calls SharedCounter.increment(), it acquires the lock on SharedCounter.class. If Thread-B tries to call increment() or getCount() (both synchronized static methods), it must wait—even though no specific SharedCounter instance is involved.
Key Difference from Instance Methods
- Instance synchronized methods lock on
this(the specific object) - Static synchronized methods lock on
ClassName.class(the Class object)
This means synchronized static and synchronized instance methods do not block each other—they use different locks.
Key Takeaway:
Synchronized static methods lock on the Class object, ensuring thread-safe access to static fields across all instances and preventing concurrent execution of any synchronized static method in that class.