BackendBench
Coffee
Spot the Bug #58

Locking on an object nobody else has

A medium Java puzzle in the threading and race conditions family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumThreading and race conditionsbuggy line: 5

Highlighted: line 5. Play this one as a puzzle without the answer.

What is wrong

A new lock object is created on every call, so no two threads ever contend for the same lock and nothing is actually protected. get uses the intrinsic lock of this, which deposit does not share either.

The fix

public synchronized void deposit(long amount) { cents += amount; }

How to avoid it next time

Synchronize on one shared, final lock object, such as this or a private final Object field.

Want the background? Read synchronized and locks in the Java concepts library.

About threading and race conditions

Without synchronization, threads can see stale values and interleave read-modify-write sequences. A volatile field gives visibility but not atomicity, and check-then-act sequences are never atomic by themselves.

In code review: For every shared variable ask who writes it, who reads it, and what protects it. Prefer atomic classes, concurrent collections and immutable objects.

More puzzles in this family

🐞 Play today's puzzleAll 132 bugs← #57#59 →

Frequently asked questions

What is the bug in "Locking on an object nobody else has"?

A new lock object is created on every call, so no two threads ever contend for the same lock and nothing is actually protected. get uses the intrinsic lock of this, which deposit does not share either. The faulty line is line 5: synchronized (new Object()) {

How do I fix it?

Replace it with: public synchronized void deposit(long amount) { cents += amount; }. Synchronize on one shared, final lock object, such as this or a private final Object field.

How do I catch threading and race conditions in code review?

For every shared variable ask who writes it, who reads it, and what protects it. Prefer atomic classes, concurrent collections and immutable objects.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need