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

Lost Updates: The Classic Problem

Illustrate how two threads reading the same value and writing back can cause one update to be lost.

Lost Updates: The Classic Problem

What you'll learn: You'll understand how two threads can simultaneously read and write a shared variable, causing one thread's update to completely disappear.

The Core Issue

When two threads perform a read-modify-write operation on the same variable without coordination, one thread's update can be completely overwritten by the other. This is called a lost update, and it's one of the most common and dangerous race conditions.

How Lost Updates Happen

Imagine this sequence with a counter starting at 10:

  1. Thread A reads the counter value: 10
  2. Thread B reads the counter value: 10 (same value!)
  3. Thread A increments its copy to 11 and writes back
  4. Thread B increments its copy to 11 and writes back

Both threads read the same initial value before either could write. The final value is 11 instead of the correct 12. Thread A's update was lost — completely overwritten by Thread B.

A Real-World Analogy

Think of two clerks updating a shared notebook. Both see "Stock: 100" written in pencil. Each grabs an eraser, does their own calculation (Clerk A: "After my sale, 99"; Clerk B: "After my sale, 99"), and writes their answer. The last one to write wins. One sale was lost from the records, even though both happened.

Why This Is Serious

Lost updates silently corrupt your data. Your counter, bank balance, or inventory becomes incorrect without any error messages. The program appears to work, but the numbers are wrong.

Key Takeaway: Lost updates occur when threads read-modify-write shared data without synchronization, causing one thread's work to be silently overwritten and leading to incorrect program state.