CAP477 · Unit 5: Concurrency and I/O
Synchronization and thread safety
8 practice questions
Key points
- synchronized gives mutual exclusion and visibility
- volatile gives visibility only
- wait/notify need the monitor
- Deadlock = circular wait; fix with lock ordering
A race condition occurs when threads read and modify shared data without coordination, so n++ (read, add, write) can lose updates. The result of unsynchronised code is unpredictable and often lower than expected.
Tools:
- `synchronized` method or block: only one thread at a time holds an object's monitor lock. Four threads each calling a
synchronized void inc()50,000 times always end at 200000.synchronized (obj) { ... }locks a chosen object; a static synchronized method locks theClassobject. - Atomic classes (
AtomicInteger): lock-free operations such asincrementAndGet,addAndGet,compareAndSet(expect, update). - `ReentrantLock`: explicit
lock()andunlock(); always unlock infinally. SupportstryLockand fairness. - `volatile`: guarantees visibility (a write is seen by other threads) but not atomicity (
count++stays unsafe). Good for stop flags. - Concurrent collections:
ConcurrentHashMap(thread-safemerge),CopyOnWriteArrayList(iteration sees a snapshot; adding during iteration is safe and the loop does not see 9),Collections.synchronizedList.
Inter-thread communication: wait(), notify(), notifyAll() must be called while holding the object's monitor, else IllegalMonitorStateException. Use wait inside a while loop that rechecks the condition (producer-consumer).
Deadlock: two threads each hold one lock and wait for the other's (thread 1 holds A wants B, thread 2 holds B wants A). They stay BLOCKED forever. Prevent it by acquiring locks in a fixed global order, using tryLock with timeouts, or avoiding nested locks.
Exam pitfall: volatile does not make i++ atomic; synchronized also gives visibility.
Try two questions
What does volatile guarantee?
- Mutual exclusion
- That a variable is never cached by the compiler
- Visibility of writes across threads, but not atomicity
- Atomicity of ++ operations
Show the answer
C. A stop flag works with volatile; a counter does not.
Which keyword gives a method mutual exclusion on the object's monitor?
- volatile
- synchronized
- transient
- final
Show the answer
B. With synchronized inc(), 4 threads x 50,000 increments always give 200000.