Race Condition in Java

Race Condition in Java

A race condition in Java occurs when two or more threads can access shared data and try to change it simultaneously. Because the threads are executing concurrently, the sequence of actions performed on the shared data can lead to inconsistent or unexpected results. This happens because the outcome of the execution depends on the non-deterministic timing of the threads’ execution.

R are problematic because they can lead to unpredictable behavior, data corruption, and difficult-to-debug issues in concurrent applications.

Race Condition

Key Points of Race Conditions:

  • Concurrent Access: Multiple threads access and manipulate shared data at the same time.
  • Non-deterministic Behavior: The result depends on the timing and sequence of thread execution, making it unpredictable.
  • Data Inconsistency: Leads to inconsistent or incorrect state of the shared data.

Example
Below is an example demonstrating a race condition:

java
class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

class CounterThread extends Thread {
    private Counter counter;

    public CounterThread(Counter counter) {
        this.counter = counter;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }

    public static void main(String[] args) {
        Counter counter = new Counter();

        Thread t1 = new CounterThread(counter);
        Thread t2 = new CounterThread(counter);

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count: " + counter.getCount());
    }
}

Explanation:

Counter Class:

    • Counter class has a private count variable and an increment() method that increments count by
    • The getCount() method returns the current value of count.

    CounterThread Class:

      • CounterThread class extends Thread and has a Counter object.
      • The run() method increments the counter 1000 times.

      Main Method

        • A Counter object is created.
        • Two CounterThread threads are created and started.
        • The main thread waits for both threads to finish using join().

        Race Condition

        • Since the increment() method is not synchronized, both threads can simultaneously access and update the count variable.
        • This concurrent access can lead to r c where the final value of count is less than expected (2000), due to overlapping increments where one thread’s increment overwrites the other’s increment.

        Homepage

        Readmore