Skip to content

Chapter 23 of 37

Synchronization

Protect shared state with monitors, locks, volatile fields, and happens-before rules.

42 minutes 10 quick checksBy Subha Prasad
Lesson 23 of 37Course navigation

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.

Which statement best describes synchronized?
Which Java term matches this description: A construct providing mutual exclusion and happens-before visibility.
Which statement best describes intrinsic lock?
Which Java term matches this description: The monitor associated with every Java object.
Which statement best describes volatile?
Which Java term matches this description: A field modifier providing visibility and ordering but not compound-operation atomicity.
Which statement best describes data race?
Which Java term matches this description: Conflicting unsynchronized accesses where at least one access writes.
Which statement best describes deadlock?
Which Java term matches this description: A cycle in which threads permanently wait for locks held by one another.

0 of 10 checks passed

Your progress is saved on this device.

Synchronization | Java Lesson | Subha Prasad