The result is 11, 12, or 13
// balance = 10
public void deposit(int amount) {
balance += amount;
}
thread1 -> deposit(1)
thread2 -> deposit(2)
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)
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)
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