Race Conditions

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Race Condition: the outcome depends on the timing of interleaved concurrent accesses. For example, two threads increment the same counter without synchronization and lose updates.

Countermeasures: atomic operations, locks, immutable data.

$$\texttt{count++}=\mathrm{load};\,\mathrm{add};\,\mathrm{store}$$

Where used

Any shared counter, cache, or collection without Happens-Before is a production bug under load. Flaky tests are often races.

Depth

A race condition occurs when the result depends on the temporal overlap of competing accesses. Even count++ consists of reading, computing, and writing. Two threads can read the same old value and lose an increment.

Correctness requires that related operations be executed atomically or under an appropriate synchronization rule. It is crucial not only to have mutual exclusion but also visibility: changes made by one thread must be observable to others after synchronization.

Difficulty levels

  1. Decompose a lost update into single steps.
  2. Identify critical sections based on shared invariants.
  3. Justify exclusion and memory visibility together.

Pitfalls

Rare reproduction is not evidence of safety. Logging or debugging can alter timing and mask the error. Also, multiple individually thread-safe methods do not automatically form an atomic overall operation together.

University approvals: 0
Tasks
Question 1

What characterizes a race condition?

Question 2

Two threads are incrementing count++ simultaneously. How can an increment be lost?

Question 3

Implement a thread-safe counter. inc and get must be synchronized.

Hint

The keyword synchronized can be directly written in the method declaration before the return type.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy