Class-Level Locks with synchronized(ClassName.class)
What you'll learn: How to synchronize on the Class object itself to protect static fields and coordinate access across all instances of a class.
The Core Idea
When you write synchronized(ClassName.class), you're acquiring a lock on the Class object itself, not on any particular instance. This is called class-level locking. Just as every object has an intrinsic lock, every Class object also has its own intrinsic lock.
This becomes essential when you need to protect static fields that are shared across all instances of a class. Since static data doesn't belong to any particular instance, locking on this wouldn't protect it across different objects.
When to Use Class-Level Locks
Use synchronized(ClassName.class) when:
- You're accessing or modifying static fields that could be read/written by multiple threads
- You need coordination that spans all instances of the class
- You want finer control than a
synchronized staticmethod provides
Syntax Example
class Counter {
private static int count = 0;
public void increment() {
synchronized(Counter.class) {
count++; // Protected by class-level lock
}
}
}
This ensures that even if you have 100 different Counter objects, only one thread at a time can execute the synchronized block across all of them.
The Analogy
Think of it like a single master key for an entire building, not just one apartment. No matter which apartment door you approach, you need that same master key—so only one person can hold it at a time for the entire building.
Key Takeaway:
Synchronizing on ClassName.class acquires a class-level lock shared by all instances, making it the right choice for protecting static fields and achieving coordination across an entire class.