Java Materials
← Core Java · Chapter 13

Monitors, explicit locks and coordination

Use a lock to protect an invariant, not merely a write. All code touching the invariant must agree on which lock protects it. Instance synchronized methods lock that instance and static synchronized methods lock its Class object. Java intrinsic monitors and ReentrantLock are reentrant, making nested acquisition by the same owner possible.

Guarded waits, monitors and Condition

Definition:

A guarded wait suspends a thread until it can reacquire the lock and verify a condition.

Explanation:

A signal does not reserve a value or transfer ownership.

Illustration image:

Guarded waits, monitors and Condition. Consumer locks · Guard false · await releases lock · Reacquire and recheckGuarded waits, monitors and ConditionSource or actorConsumer locksFirst boundaryGuard falseInspected stateawait releases lockObservable effectReacquire and recheck
Consumer locks · Guard false · await releases lock · Reacquire and recheck

Example:

Worked Java example · see surrounding context in notes
lock.lockInterruptibly();
try {
    while (items.isEmpty()) notEmpty.await();
    return items.removeFirst();
} finally {
    lock.unlock();
}

Expected behavior. A spurious wakeup or a faster consumer cannot make this remove from an empty queue.

Internal working:

The waiter must reacquire the same lock and retest the predicate. A Condition allows independent wait sets for not-empty and not-full. ReentrantLock can provide interruptible or bounded acquisition. Always balance successful acquisition with a finally release.

Interview questions:

Why is a signal followed by another guard check?

Wakeups can be spurious, or another thread can take the item before the waiter reacquires the lock.

Read-write locks and optimistic validation

Definition:

An optimistic read samples state and verifies that no conflicting write invalidated its assumptions.

Explanation:

Read locks allow concurrent readers but can impose bookkeeping costs.

Illustration image:

Read-write locks and optimistic validation. Optimistic stamp · Sample fields · validate stamp · Fallback read lockRead-write locks and optimistic validationSource or actorOptimistic stampFirst boundarySample fieldsInspected statevalidate stampObservable effectFallback read lock
Optimistic stamp · Sample fields · validate stamp · Fallback read lock

Example:

Worked Java example · see surrounding context in notes
long stamp = lock.tryOptimisticRead();
int candidate = balance;
if (!lock.validate(stamp)) {
    stamp = lock.readLock();
    try { candidate = balance; }
    finally { lock.unlockRead(stamp); }
}

Expected behavior. The returned value was protected either by successful validation or by a read lock.

Internal working:

Downgrading write to read can be useful; upgrading read to write can wait forever. StampedLock optimistic reads may see intermediate values. Copy fields first, validate before using them and re-read under a real read lock if validation fails. Do not call side-effecting code from an unvalidated read.

Interview questions:

When is a StampedLock read usable?

Only after validation succeeds, or after the values are reread under a real read lock.

Deadlock, fairness and AQS

Definition:

A deadlock is a cycle of dependencies that prevents participants from making progress.

Explanation:

Coarse locks simplify invariant reasoning; striped locks reduce unrelated contention but make cross-stripe operations harder.

Illustration image:

Deadlock, fairness and AQS. Both choose account 1 · One acquires first · Other waits · Owner locks account 2Deadlock, fairness and AQSSource or actorBoth choose account 1First boundaryOne acquires firstInspected stateOther waitsObservable effectOwner locks account 2
Both choose account 1 · One acquires first · Other waits · Owner locks account 2

Example:

Worked Java example · see surrounding context in notes
Account first = a.id < b.id ? a : b;
Account second = first == a ? b : a;
synchronized (first) {
    synchronized (second) { applyTransfer(a, b); }
}

Expected behavior. Opposite-direction transfers acquire the same lock first, preventing that particular lock-order cycle.

Internal working:

Establish one lock order and avoid blocking external I/O while holding shared locks. Fair acquisition can trade throughput for reduced overtaking. AQS underlies many synchronizers by managing state and queued waiters; LockSupport provides park/unpark permits, not a condition predicate.

Interview questions:

How does stable lock ordering prevent an opposing-transfer deadlock?

Both transfers acquire the same lower-ID lock first, so they cannot hold one another’s first required locks in opposite order.

Reference subtopics

Guarded waits and conditions

wait and notify require ownership. wait releases the monitor while suspended and reacquires it before returning. notify wakes one eligible waiter and notifyAll wakes all, but none can reconsider the condition until the notifier releases ownership. Use while because wakeups can be spurious or another thread can consume the condition first. Condition separates multiple queues such as notEmpty and notFull.

Explicit and read/write locks

ReentrantLock supports tryLock, bounded acquisition and lockInterruptibly. Unlock in finally only after acquisition. ReentrantReadWriteLock allows concurrent readers and exclusive writers. Downgrade by acquiring read while holding write, then releasing write. An in-place read-to-write upgrade can deadlock. StampedLock is non-reentrant; read fields under an optimistic stamp, validate it and fall back to a read lock if invalid.

Fairness and low-level mechanics

Choose lock granularity based on invariant scope and measured contention. Stripe independent keys but define consistent ordering for multi-lock operations. Fair locks can reduce overtaking with throughput cost and do not guarantee OS scheduling fairness. AQS supports state and waiter queues for many synchronizers. LockSupport supplies park/unpark permits; callers still need a condition loop.

Run the complete Java labs ↗ · Java reference ↗