CodeGym /Courses /JAVA 25 SELF /Breakdown of common synchronization mistakes

Breakdown of common synchronization mistakes

JAVA 25 SELF
Level 52, Lesson 4
Available

1. Forgotten unlock/release: a trap for the inattentive

One of the trickiest mistakes when using modern synchronization tools such as ReentrantLock or Semaphore is forgetting to call unlock() or release(). If you don’t release the lock, other threads will wait for it to be released... forever. The program will hang, and you’ll stare at the screen for a long time trying to figure out why nothing happens.

Consider an example with ReentrantLock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Counter {
    private int count = 0;
    private final Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        // Oops! Forgot unlock()—now everyone will hang!
        count++;
    }
}

It looks innocent, but if you call increment() multiple times from different threads, after the first call the remaining threads will wait for the lock to be released indefinitely.

To avoid this, use a try-finally construct:

public void increment() {
    lock.lock();
    try {
        count++;
    } finally {
        lock.unlock();
    }
}

Now, even if an exception occurs in the middle of the method, the lock is guaranteed to be released.

It’s like someone occupied a restroom (locked it from the inside), then forgot to unlock the door and climbed out the window. Everyone else will wait until that person comes out... Don’t do that!

2. Synchronizing on the wrong object: “Oops, locked the wrong thing!”

In Java, the synchronized keyword can block access to a particular object. But if you choose the wrong object to lock on, synchronization won’t work as you expect.

Mistake #1: synchronizing on a local variable

public void doSomething() {
    Object lock = new Object();
    synchronized (lock) {
        // A new object every time—no synchronization!
        // Threads don’t wait for each other.
        // The critical section isn’t protected!
    }
}

Here, each thread creates its own lock object. As a result, no real locking happens—threads enter the critical section simultaneously.

Correct:

private final Object lock = new Object();

public void doSomething() {
    synchronized (lock) {
        // Now all threads use the same lock object
        // and actually wait for each other.
    }
}

Mistake #2: synchronizing on a string literal

public void doSomething() {
    synchronized ("lock") {
        // String literals are interned: different parts of the program can
        // accidentally synchronize on the same string!
    }
}

Conclusion:
Synchronize only on private, purpose-made lock objects that aren’t used anywhere else.

3. Deadlock: “You go first—no, you go, and both stop”

Deadlock (mutual blocking) is a classic. Two (or more) threads sequentially acquire different locks and wait for each other until the program grinds to a halt.

Example:

public class DeadlockExample {
    private final Object lockA = new Object();
    private final Object lockB = new Object();

    public void method1() {
        synchronized (lockA) {
            // Wait a bit for the sake of the experiment
            try { Thread.sleep(50); } catch (InterruptedException e) {}
            synchronized (lockB) {
                // ...
            }
        }
    }

    public void method2() {
        synchronized (lockB) {
            try { Thread.sleep(50); } catch (InterruptedException e) {}
            synchronized (lockA) {
                // ...
            }
        }
    }
}

If one thread calls method1() and another calls method2(), the first thread will acquire lockA and wait for lockB, and the second will do the opposite. As a result, both will wait for each other forever.

How to avoid it?

  • Always acquire locks in the same order across all threads.
  • Minimize the number of locks held at the same time.
  • Use diagnostic tools (for example, jstack) if the program is stuck.

Analogy:
It’s like two people meeting in a narrow hallway, each willing to yield, but only if the other yields first. In the end, both stand and wait until someone gives in.

4. Over-synchronization: “Better safe than sorry?”—not always!

Sometimes developers, fearing errors, synchronize everything in sight. As a result, performance drops and the benefit is zero.

Example:

public synchronized void add(int value) {
    // There’s only one line here that doesn’t require synchronization!
    System.out.println("Added: " + value);
}

In this case, synchronization isn’t needed: output via System.out.println is already thread-safe, and the method itself doesn’t work with shared resources.

Where is this critical?
If you synchronize methods that are called frequently and don’t need protection, you dramatically reduce the program’s performance. Threads line up in a queue even though they could run in parallel.

Best practice:
Synchronize only what’s truly necessary. The critical section should be as small as possible.

5. Misusing volatile: “Visibility yes, atomicity no!”

In Java, the volatile modifier guarantees that changes to a variable are visible to all threads. But it does not guarantee atomicity of operations.

Mistake:

private volatile int counter = 0;

public void increment() {
    counter++; // Not atomic!
}

The counter++ operation consists of reading the value, incrementing it, and writing it back. If two threads execute this code at the same time, the final value may be less than expected.

Correct:
For atomic operations, use synchronized, AtomicInteger, or other thread-safe classes.

import java.util.concurrent.atomic.AtomicInteger;

private final AtomicInteger counter = new AtomicInteger();

public void increment() {
    counter.incrementAndGet();
}

When to use volatile?
For simple flags (for example, “shut down”), when atomicity isn’t required.

1
Task
JAVA 25 SELF, level 52, lesson 4
Locked
Reliable transaction accounting system 💳
Reliable transaction accounting system 💳
1
Task
JAVA 25 SELF, level 52, lesson 4
Locked
Centralized Office Printer 🖨️
Centralized Office Printer 🖨️
1
Survey/quiz
Thread synchronization, level 52, lesson 4
Unavailable
Thread synchronization
Thread synchronization
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION