previous | start | next

Scenario to Explain Non-zero Result: Race Condition

  1. The first thread t1 executes the lines
    System.out.print("Depositing " + amount);
    double newBalance = balance + amount;
    The balance field is still 0, and the newBalance local variable is 100
  2. t1 reaches the end of its time slice and t2 gains control
  3. t2 calls the withdraw method which withdraws $100 from the balance variable;
    it is now -100
  4. t2 goes to sleep
  5. t1 regains control and picks up where it left off; it executes:
    System.out.println(", new balance is " + newBalance);
    balance = newBalance;
    The balance is now 100 instead of 0 because the deposit method used the OLD balance

previous | start | next