Junior — Middle
How does the value of an integer variable change when incremented concurrently by multiple threads?
sobes.tech AI
Answer from AI
When multiple threads increment a shared integer variable without synchronization, data races can occur. This means the final value might be less than expected because read, increment, and write operations are not atomic.
For example, if two threads read the value 5 simultaneously, both increment to 6 and write back, the final value will be 6 instead of 7.
To prevent this, synchronization mechanisms should be used, such as the synchronized keyword or atomic classes from java.util.concurrent.atomic:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
This approach guarantees correct incrementing in a multithreaded environment.