Sobes.tech
Senior

What is a race condition?

sobes.tech AI

Answer from AI

Race condition occurs when multiple threads or processes access and modify shared data simultaneously without proper synchronization, leading to unpredictable program behavior.

For example, if two threads increment a shared counter at the same time without locks, the final value may be incorrect.

Example in Java:

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 value of count may be less than expected due to a race condition.

To prevent this, synchronization is used, for example, the synchronized keyword or atomic classes from java.util.concurrent.atomic.