Lesson content
Read, practise, then check your understanding
A data race arises from conflicting accesses without a happens-before relationship. synchronized provides mutual exclusion and visibility through an object’s intrinsic monitor.
Atomic invariants
final class Counter {
private int value;
synchronized void increment() { value++; }
synchronized int value() { return value; }
}
Lock every access participating in one invariant and keep critical sections short. volatile makes individual reads/writes visible and ordered but does not make value++ atomic. Lock types add timed, interruptible, and multi-condition control; unlock in finally. Prevent deadlock with consistent lock ordering and avoid calling unknown code while holding a lock. Immutable objects and thread confinement remove synchronization needs entirely.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.