Sub topic 2
Synchronized Methods
The last chapter showed that count++ can lose updates when two threads run it at once. This chapter covers four tools that fix that problem.
Synchronized Methods
A lock is a token that only one thread can hold at a time. The keyword synchronized on a method means that a thread must hold the object's lock before it can run that method.
public class SafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
}Only one thread at a time can be inside increment(), so no update is lost. Taking the lock also makes get() see the latest value.
Synchronized Blocks and Private Lock Objects
A synchronized block locks only a few lines, not the whole method. Code that holds the lock for less time makes other threads wait less.
import java.util.ArrayList;
import java.util.List;
public class EventLog {
private final Object lock = new Object();
private final List<String> events = new ArrayList<>();
public void add(String event) {
String entry = System.currentTimeMillis() + " " + event;
synchronized (lock) {
events.add(entry);
}
}
public int size() {
synchronized (lock) {
return events.size();
}
}
}The lock object is private, so code outside the class cannot take it and block your class.
How Intrinsic Locks Work: Monitors and Reentrancy
Every Java object has a built-in lock. It is called an intrinsic lock, or monitor. Intrinsic locks are reentrant. This means a thread that already holds a lock can take it again. So a synchronized method can call another synchronized method on the same object without blocking itself.
volatile: Visibility Without Locking
A volatile field is one whose writes are always visible to other threads.
public class Worker implements Runnable {
private volatile boolean running = true;
public void stop() {
running = false;
}
@Override
public void run() {
while (running) {
// do a unit of work
}
}
}Atomic Variables: AtomicInteger and Friends
An atomic class does an operation such as read-add-write as one step that cannot be split, without a lock.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private final AtomicInteger count = new AtomicInteger();
public int increment() {
return count.incrementAndGet();
}
public int get() {
return count.get();
}
}Exercise
Why is a volatile int counter still unsafe when two threads call count++ on it?
Show answer
The count++ statement is three steps: read, add, and write. volatile makes each write visible to other threads, but it does not stop two threads from reading the same old value. Use AtomicInteger or synchronized instead.
Exercise
A synchronized method calls another synchronized method on the same object. Why doesn't the thread block itself?
Show answer
Intrinsic locks are reentrant. A thread that already holds the lock can take it again.