Ch. 7 · Java

Java Synchronized Blocks and Shared Invariants

Java Synchronized Blocks and Shared Invariants. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

A lock protects an invariant only when every relevant access follows the same locking discipline. Locking unrelated objects does not coordinate writers.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: Update an account’s balance and ledger entry within one protected region. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Write the invariant

Balance and ledger must agree as one transition.

Step 2: Share the locking discipline

All relevant reads and writes must coordinate through the same lock.

Step 3: Keep slow work outside

Avoid holding the lock through unnecessary external I/O; preserve correctness when separating phases.

Worked scenario

Update an account’s balance and ledger entry within one protected region.

Writer A updates balance under one lock while reader B uses another. Those locks do not coordinate. Even locking only writers leaves readers able to observe a partially updated multi-field state unless reads follow the same discipline or consume an appropriately published snapshot.

Common mistake

Locking only writes can still leave unsynchronized readers with inconsistent observations.

Verify the behavior

Trace competing read and write interleavings, checking the invariant at every observable point.

Interview exercise

Choose the lock boundary.

Answer and reasoning

Protect the complete state transition and document the shared lock, while keeping slow external I/O outside where possible.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc