Skip to content

Instantly share code, notes, and snippets.

@gc-garcol
Last active July 9, 2024 15:08
Show Gist options
  • Save gc-garcol/bd4d70375cbe632e5370f894aaf51162 to your computer and use it in GitHub Desktop.
Save gc-garcol/bd4d70375cbe632e5370f894aaf51162 to your computer and use it in GitHub Desktop.
race data vs race condition

Race data example

The result is 11, 12, or 13

// balance = 10
public void deposit(int amount) {
  balance += amount;
}
thread1 -> deposit(1)
thread2 -> deposit(2)

Not race condition example

If current balance is 100, then not race condition. The result is 90

// balance = 100
public synchronized void deposit(int amount) {
  balance += amount;
}

public synchronized void withdraw(int amount) {
  if (balance >= amount) {
    balance -= amount;
  }
}
thread1 -> deposit(10)
thread2 -> withdraw(20)

race condition example

But when the current balance is 10. Then:

We don't know the final result is, it maybe 0 (deposit success, withdraw success) or 20 (withdraw fail, deposit success)

// balance = 10

public synchronized void deposit(int amount) {
  balance += amount;
}

public synchronized void withdraw(int amount) {
  if (balance >= amount) {
    balance -= amount;
  }
}
thread1 -> deposit(10)
thread2 -> withdraw(20)

How to prevent race condition

Queue is not a solution, althought items in queue are ordered, but the requests before pushed into queue are not ordered.

How use solve it?

  • Using a priority queue (min-heap), the compare strategy is:
    • Compare pushed time.
    • Compare hashCode or something else
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment