Junior — Middle
What happens when multiple threads simultaneously modify a single variable inside a loop?
sobes.tech AI
Answer from AI
When multiple threads simultaneously modify a single variable inside a loop without synchronization, a race condition occurs. This leads to unpredictable results because read and write operations can overlap.
For example, if two threads simultaneously increment a counter:
int counter = 0;
// In both threads:
counter = counter + 1;
Since the increment operation is not atomic (it consists of reading, incrementing, and writing), the final value may be less than expected.
To avoid this, synchronization mechanisms should be used, such as the synchronized keyword or atomic classes from java.util.concurrent.atomic:
AtomicInteger counter = new AtomicInteger(0);
// In threads:
counter.incrementAndGet();
This guarantees correct updating of the variable without data loss.