Sub topic 3
Deadlock and How Lock Ordering Prevents It
Deadlock
A deadlock happens when two threads each hold a lock and wait for the other's lock. Neither thread can move on, so both stop forever. In the diagram below, Thread 1 holds lock A and wants lock B, while Thread 2 holds lock B and wants lock A.
To prevent this, every thread should take locks in the same order. If all threads take lock A before lock B, the circle can never form.
public class OrderedLocking {
private static final Object LOCK_A = new Object();
private static final Object LOCK_B = new Object();
static void doWork() {
synchronized (LOCK_A) {
synchronized (LOCK_B) {
// always A first, then B
}
}
}
}Concurrent Collections
A concurrent collection is a list or map built to be shared safely between threads. ConcurrentHashMap has methods such as merge that do a whole update in one atomic step. That avoids the race in a "get, then put" sequence, where another thread can change the value between your two calls.
import java.util.concurrent.ConcurrentHashMap;
public class WordCounts {
private final ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
public void record(String word) {
counts.merge(word, 1, Integer::sum);
}
}Immutability
An immutable object is an object that cannot change after you create it. You make one by marking the class and all of its fields final and leaving out setters. Because nothing in it can change, threads can share it without any locks.
Explicit Locks with ReentrantLock
ReentrantLock is a lock object that you lock and unlock yourself. Always put unlock() inside a finally block. A finally block runs even when the code throws an exception, so the lock always gets released.
The Java Memory Model and Happens-Before
The Java Memory Model is the set of rules that decides when one thread can see another thread's writes. "Happens-before" means that a write is guaranteed to be visible to a later action. Unlocking a lock, writing a volatile field, starting a thread, and joining a thread each create a happens-before link.
wait and notifyAll
wait() pauses a thread until another thread calls notifyAll(). Call wait() inside a while loop that checks your condition, and check the condition again each time the thread wakes up.
Thread Confinement and ThreadLocal
Thread confinement means keeping data inside a single thread so that no other thread ever touches it. ThreadLocal gives each thread its own private copy of a value.
Read-Write Locks
A ReentrantReadWriteLock lets many threads read at the same time, but only one thread can write, and no one reads while it writes. Use it for data that is read often and changed rarely.
Exercise
Thread 1 locks A then B. Thread 2 locks B then A. What can go wrong, and how do you fix it?
Show answer
They can deadlock if each one gets its first lock and then waits for the other's. Fix it by making both threads lock A first, then B.