Course contentsShow
← Java
Lesson 2648 of 2,87049. Synchronization and LockingFree lesson

Race Conditions in Object State

Show how unsynchronized access to multiple related fields can leave objects in inconsistent states.

Race Conditions in Object State

What you'll learn: How unsynchronized access to multiple related fields can leave objects in inconsistent states, even when individual operations appear safe.

The Problem with Multi-Field Objects

You've seen race conditions affect single variables like counters. But the real danger emerges when objects have multiple fields that must remain consistent with each other. When threads modify these fields without synchronization, they can leave the object in an impossible or invalid state—even if each individual field assignment is atomic.

Why Multiple Fields Create Risk

Imagine a BankAccount class with two fields: balance and transactionCount. After every deposit or withdrawal, both should update together:

class BankAccount {
    private int balance = 0;
    private int transactionCount = 0;

    // UNSAFE - Race condition!
    void deposit(int amount) {
        balance += amount;           // Step 1
        transactionCount++;          // Step 2
    }
}

The race: Thread A completes step 1, then gets interrupted. Thread B runs both steps. Thread A resumes and completes step 2. Now transactionCount is wrong—it doesn't match the actual number of completed transactions.

The Consistency Window

Between updating related fields, there's a consistency window where the object is temporarily invalid. In a single-threaded program, this is harmless—no one sees the intermediate state. But with concurrent threads, another thread might read the object during that window, observing contradictory values.

Analogy: It's like updating a scoreboard where points and fouls must match. If you update points first, someone glancing mid-update sees impossible stats: "50 points, 0 fouls."

Key Takeaway: Objects with multiple related fields require synchronization across all field updates to maintain invariants, because unsynchronized access creates windows where the object's state is inconsistent and observable by other threads.