synchronized
synchronized is Java's built-in lock. A thread that enters a synchronized block holds the monitor of an object. Other threads that need the same monitor wait. Exit releases it and publishes writes.
Detailed Explanation
Two threads incrementing count++ can both read 7 and both write 8. The increment is not atomic. synchronized (this) { count++; } makes the read-modify-write a critical section. Only one thread runs that block at a time for a given lock object.
There are two forms. A synchronized instance method locks this. A synchronized static method locks the Class object. A synchronized block locks the object you name, which should be a private final field, not a public string or this if callers might lock on the same instance.
synchronized is also a visibility barrier. Writes in the block happen-before the next thread that acquires the same lock sees them. You do not need volatile on fields that are only read and written inside the same lock. You still need a lock (or another safe publication) for every access, including reads. A locked write plus an unlocked read is a race.
Reentrancy is allowed: a thread that holds a monitor can enter another synchronized block on the same object. That is how a synchronized method can call another. The monitor has a count; it releases when the count hits zero.
You reach for synchronized for simple mutual exclusion on one object. You reach for ReentrantLock when you need try-lock, interruptible lock, or multiple condition queues. You reach for concurrent collections and atomics when the critical section is a single counter or map update.
The cost of a lock is contention: threads park and wake. The cost of locking this is that foreign code can lock your instance and deadlock you. The cost of synchronizing on an interned String is a lock shared with unknown code. The cost of a huge synchronized method is serializing work that could be finer-grained.
wait and notify must be called on the same monitor you hold. That pair is older than Condition and easier to misuse.
Code Examples
public class Counter {
private int n;
public synchronized void inc() {
n++; // one thread at a time on this instance
}
public synchronized int get() {
return n;
}
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t = new Thread(() -> {
for (int i = 0; i < 10_000; i++) {
c.inc();
}
});
t.start();
for (int i = 0; i < 10_000; i++) {
c.inc();
}
t.join();
System.out.println(c.get()); // prints: 20000
}
}public class PrivateLock {
private final Object lock = new Object();
private int n;
public void inc() {
synchronized (lock) { // callers cannot acquire this lock
n++;
}
}
}Common Gotchas
Every access must use the same lock
an unsynchronized getter races with a synchronized setter.
Locking on a string literal shares the interned object
use a private `new Object()`.
`synchronized (this)` lets outsiders lock you
prefer a private lock field.
Synchronized does not make objects inside the block thread-safe
it only serializes the block.