nerdexam
Oracle

1Z0-819 · Question #52

Given public class Foo { private final ReentrantLock lock = new ReentrantLock(); private State state; public void foo() throws Exception { try { lock.lock(); state.mutate(); } finally {…

The correct answer is C. Replace the constructor call with new ReentrantLock (true). Option C introduces a fair ReentrantLock (new ReentrantLock(true)), which guarantees threads acquire the lock in FIFO order. Without fairness, a non-fair lock can repeatedly grant access to new threads, starving waiting threads indefinitely - meaning some threads never make…

Concurrency

Question

Given public class Foo { private final ReentrantLock lock = new ReentrantLock(); private State state; public void foo() throws Exception { try { lock.lock(); state.mutate(); } finally { lock.unlock(); } } } What is required to make the Foo class thread safe?

Options

  • ANo change is required;
  • BMake the declaration of lock static.
  • CReplace the constructor call with new ReentrantLock (true).
  • DMove the declaration of lock inside the foo method.

How the community answered

(39 responses)
  • A
    8% (3)
  • B
    5% (2)
  • C
    69% (27)
  • D
    18% (7)

Explanation

Option C introduces a fair ReentrantLock (new ReentrantLock(true)), which guarantees threads acquire the lock in FIFO order. Without fairness, a non-fair lock can repeatedly grant access to new threads, starving waiting threads indefinitely - meaning some threads never make progress, which violates the liveness requirement that exam contexts include under "thread safety."

A is wrong because the default (unfair) lock permits starvation, so a change is necessary. B is wrong because making lock static would share a single lock across all Foo instances, introducing unnecessary cross-instance contention when each instance has its own independent state - over-synchronization, not correct synchronization. D is catastrophically wrong because declaring lock inside foo() creates a brand-new ReentrantLock on every call; since no two threads would ever compete on the same lock object, mutual exclusion is completely lost.

Memory tip: Think "fair = FIFO = no starvation." When an exam asks about thread safety with ReentrantLock, look for starvation risk as the hidden flaw - the true constructor argument is the giveaway that fairness (and thus liveness) is the concept being tested.

Topics

#ReentrantLock#fair vs non-fair locks#thread safety#lock configuration

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice