Middle
Tell me about race condition.
sobes.tech AI
Answer from AI
Race condition occurs when multiple threads or processes access a shared resource simultaneously without proper synchronization, and the final result depends on the order of execution of these operations.
In Java, this often manifests when working with shared variables without using synchronization mechanisms (synchronized, volatile, atomic classes). For example, if two threads increment a counter simultaneously without locks, the final value may be less than expected.
Example of race condition:
public class Counter {
private int count = 0;
public void increment() {
count = count + 1; // non-atomic operation
}
public int getCount() {
return count;
}
}
// If multiple threads call increment() simultaneously, the final count may be less than expected.
To avoid race conditions, synchronization, atomic operations, or other access control mechanisms are used.