Sobes.tech
Senior

What is a race condition? How to deal with it? Provide an example and name the ways to handle it in Java.

sobes.tech AI

Answer from AI

Race condition is a situation in multithreaded programs where multiple threads simultaneously access a shared resource (such as a variable or file), and at least one of them modifies this resource. Due to the lack of synchronization, the final state of the resource becomes unpredictable and depends on the order of thread execution.

Example of race condition in Java:

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 value of count may be less than expected.

Ways to combat race condition in Java:

  • Synchronization (synchronized) — blocks access to critical sections of code, allowing only one thread to execute them.

    public synchronized void increment() {
        count++;
    }
    
  • Using atomic classes from java.util.concurrent.atomic — for example, AtomicInteger, which provides atomic operations without locks.

    private AtomicInteger count = new AtomicInteger(0);
    public void increment() {
        count.incrementAndGet();
    }
    
  • Lock interface (e.g., ReentrantLock) — a more flexible locking mechanism.

  • Using thread-safe collections and data structures.

  • Avoid shared access to mutable data, use immutable objects or local copies.

Thus, race condition occurs due to the lack of proper synchronization of access to shared resources, and in Java, mechanisms such as synchronization, atomic operations, and locks are used to address it.