Junior — Middle
How to ensure returning the value 2000 when two threads simultaneously increment a volatile variable initially set to zero?
sobes.tech AI
Answer from AI
A variable declared as volatile guarantees visibility of changes between threads but does not ensure atomicity of operations. When two threads increment the variable simultaneously, there can be a race condition, and the final value may be less than expected.
To guarantee that after two concurrent increments the value will be 2000, atomic operations or synchronization should be used.
In Java, you can use the AtomicInteger class from the java.util.concurrent.atomic package:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.addAndGet(1000); // increase by 1000
}
public int getCount() {
return count.get();
}
}
If two threads call increment(), the final value will be 2000 without loss.
Alternatively, a synchronized method can be used:
private int count = 0;
public synchronized void increment() {
count += 1000;
}
But AtomicInteger is preferred for performance and simplicity.