DEV Community

Gowtham Kalyan
Gowtham Kalyan

Posted on

What is Race Condition in Java?

A Race Condition occurs when multiple threads access and modify shared data at the same time, and the final result depends on the order in which threads execute.

Because thread execution timing is unpredictable, it can lead to incorrect or inconsistent results.


πŸ”Ή Simple Definition

πŸ‘‰ When two or more threads β€œrace” to update the same resource without proper synchronization, a race condition happens.


πŸ”Ή Example of Race Condition

class Counter {
    int count = 0;

    void increment() {
        count++;   // Not thread-safe
    }
}
Enter fullscreen mode Exit fullscreen mode

If two threads execute increment() simultaneously:

  1. Thread A reads value β†’ 0
  2. Thread B reads value β†’ 0
  3. Thread A updates β†’ 1
  4. Thread B updates β†’ 1

βœ… Expected result: 2
❌ Actual result: 1

This is a race condition.


πŸ”Ή Why Race Condition Happens?

  • Shared mutable data
  • Multiple threads running concurrently
  • Lack of synchronization
  • Non-atomic operations (count++ is not atomic)

πŸ”Ή How to Prevent Race Condition?

1️⃣ Using synchronized

synchronized void increment() {
    count++;
}
Enter fullscreen mode Exit fullscreen mode

2️⃣ Using Atomic Classes

AtomicInteger count = new AtomicInteger();

count.incrementAndGet();
Enter fullscreen mode Exit fullscreen mode

3️⃣ Using Locks (ReentrantLock)

Provides better control than synchronized blocks.


πŸ”Ή Real-Time Examples

  • Bank account balance updates
  • Ticket booking systems
  • Inventory management systems
  • Multi-user web applications

πŸš€ Promotional Content

Learn advanced multithreading concepts like synchronization, race conditions, and real-world concurrency handling in No 1 Java Real Time Projects Online Training in ammerpet.

Top comments (0)