Video in progress
Do a static synchronized method and a regular synchronized method block each other?
No. An instance method takes the monitor of the this object, while a static method takes the monitor of the Klass.class object. These are two different locks, so they can run in parallel.
📖 Answer
class Stats {
private static int total;
private int local;
public synchronized void incLocal() { local++; } // lock: this
public static synchronized void incTotal() { total++; } // lock: Stats.class
}
One thread can be in incLocal() while another is in incTotal(), and they don't wait for each other.
A typical bug comes from this:
public synchronized void reset() {
total = 0; // a static field, but the lock is this!
}
reset() locks this, while incTotal() locks Stats.class. Both write to total at the same time, and a race appears. On top of that, every instance of Stats has its own monitor, so reset() on two different objects runs in parallel too.
The rule: all code that protects one piece of data should use one lock object. Often the cleanest way is a separate private static final Object LOCK = new Object(); and synchronized (LOCK) everywhere.
Sign up to mark studied questions and save your progress.