Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Is this counter thread-safe when two Counter instances are used from different threads?

Java
class Counter {
private static int total;
public synchronized void add() {
total++;
}
}

No. A synchronized instance method locks the Counter instance it is called on, but total is static, so it is shared by all instances. Two threads using two different Counter objects hold two different locks and race on total, losing increments. The fix is to guard total with one lock used by every access, for example a static synchronized method, a synchronized (Counter.class) block, or a static AtomicInteger.

Why this question is asked

This tiny class is a favourite interview question because it looks correct at a glance: the method that changes the field is synchronized, so where is the problem? The problem is that the lock and the data belong to different things, and that mistake appears in real code in many forms. In this answer, we will recap what each part of the class means, reproduce the race with two instances, see why the two locks do not help each other, fix it three ways, and finish with the general rule that one lock must guard each piece of shared data.

1A Quick Recap of the Two Parts

The class has two parts that work at different levels. The field total is static, which means it belongs to the Counter class itself: there is exactly one total in the JVM, however many Counter objects we create. The method add() is an instance method, so we call it on a particular object, and because it is synchronized, it acquires the monitor of that object, this, before running.

So the lock is per instance and the data is per class. That mismatch is the whole bug. Also recall that total++ is not one step: it reads total, adds 1, and writes it back. If two threads interleave those steps, one increment is lost.

2Reproducing the Race

We can see the problem with two threads, each using its own Counter instance and calling add() 100,000 times.

Java
class Counter {
private static int total;
public synchronized void add() { total++; } // locks this, not the class
static int total() { return total; }
}
Counter c1 = new Counter();
Counter c2 = new Counter();
Thread t1 = new Thread(() -> { for (int i = 0; i < 100_000; i++) c1.add(); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 100_000; i++) c2.add(); });
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(Counter.total()); // often less than 200000, for example 137412
Step throughTwo locks, one shared field
Thread 1c1 monitortotalc2 monitorThread 2
lock c1
lock c2
read total = 5
read total = 5
write 6
write 6
unlock c1
unlock c2

8 messages in order. Play them, or step through them one at a time.

Both threads hold a lock, but not the same lock, so one increment is lost.

If both threads used the same instance c1, the result would always be 200,000, because both would need c1's monitor and would take turns. With c1 and c2, thread 1 holds c1's monitor and thread 2 holds c2's, both at the same time, and both are inside total++ together. The exact number varies from run to run, which is typical of a race.

3Why the Two Locks Do Not Help Each Other

A monitor only makes threads wait for other threads that want the same monitor. The JVM has no idea that add() touches a static field; it simply locks the object the method was called on. So synchronized here protects instance state that does not exist, and leaves the shared static state unprotected.

Notice that the visibility guarantee breaks too. The happens-before rule of synchronized applies between an unlock and a later lock of the same monitor. Thread 2 never locks c1, so it has no guarantee of seeing thread 1's writes to total at all.

4Three Ways to Fix It

Every fix has the same idea: make all access to total go through one lock that matches the data's scope, which is the class. The first two fixes use the monitor of the Class object, and the third replaces the lock with an atomic operation.

Java
// Fix 1: a static synchronized method locks Counter.class
public static synchronized void add() { total++; }
// Fix 2: keep the instance method, but lock the class explicitly
public void add() {
synchronized (Counter.class) { total++; } // same lock for every instance
}
// Fix 3: no lock at all, an atomic counter
private static final AtomicInteger total = new AtomicInteger();
public void add() { total.incrementAndGet(); } // one atomic step
// each fix prints 200000 every time

Fixes 1 and 2 work only if every other place that reads or writes total also locks Counter.class, including the total() getter, which must become static synchronized or read inside the same block. Fix 3 is usually the best for a plain counter: incrementAndGet is a single atomic operation, it is visible to all threads, and there is no lock to forget. For very high contention, LongAdder spreads updates across cells and is faster still, at the cost of a slightly more expensive sum().

One more refinement for fix 2: locking Counter.class is visible to any code in the JVM, which could also lock it. A private static final Object lock = new Object() is safer, because only our class can use it.

5The General Rule: Lock Scope Must Match Data Scope

The lesson goes beyond counters. For each piece of shared mutable data, we decide which lock guards it, and every access, reads and writes, uses that one lock. Static data needs a class-level lock; instance data can use the instance's lock. Writing the rule down helps, for example with an @GuardedBy("lock") annotation, which tools such as Error Prone can check.

When we review code, we look for the data first and the lock second: what is shared, and is every access to it under the same lock? That question finds this bug immediately, while looking only at whether methods are synchronized does not.

6Follow-up questions

Would making total volatile fix it?

No. volatile makes every read see the latest write, but total++ is still a read, an add and a write as separate steps, so two threads can both read 5 and both write 6. volatile fixes visibility, not atomicity.

Is it ever correct to have a synchronized instance method that changes static data?

Only if every access to that static data, from every instance and every static method, also goes through one common lock, which an instance method on its own cannot provide. In practice it is a code smell that reviewers should question.

Why not just use one shared Counter instance everywhere?

That would also make the original code correct, since all threads would lock the same object. But the safety would then depend on how callers use the class, which is fragile. A class should be thread-safe by its own design, not by an unwritten rule about how many instances exist.

7Conclusion

In this answer, we saw that the Counter is not thread-safe across instances, because the synchronized instance method locks each instance while total is one static field shared by all of them. Two threads with two instances hold two different locks and race on total++, losing increments and visibility. The fixes use one lock that matches the data's scope, a static synchronized method or synchronized (Counter.class), or replace the lock with a static AtomicInteger. The general rule is that the same lock must guard every access to a given piece of shared data.

What to say in the interviewAbout 80 seconds aloud

Open with

No, it is not thread-safe across instances. The synchronized instance method locks this, the particular Counter it is called on, but total is static, so there is one total shared by all instances.

Then, if they want more

If thread one calls add on c1 and thread two calls add on c2, they hold two different monitors and can be inside total++ at the same time. total++ is a read, an add and a write, so both can read 5 and both write 6, and we lose increments.

A quick test with two instances and 100,000 increments each usually prints less than 200,000. There is also no visibility guarantee, because happens-before only connects an unlock and a lock of the same monitor. To fix it, the lock has to match the data.

I could make add static synchronized, which locks Counter.class, or keep it an instance method and synchronize on Counter.class or, better, a private static final lock object. In both cases the getter must use the same lock.

For a simple counter I would use a static AtomicInteger with incrementAndGet, or LongAdder under heavy contention, because there is no lock to get wrong. The general rule is that every access to a piece of shared data uses the same lock.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Is this counter thread-safe when two Counter instances are used from different threads?": https://scrivio-interview-library.netlify.app/java/synchronization/4cc2552abd/