Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 2 of 7
Withdrawal 250.0
Withdrawal 2000.0
Deposit 2000.0
Deposit 2000.0
Deposit 250.0
The program definitely has a problem. The withdrawal thread should not be simulating ,$2000 withdrawals, and the deposit thread should not be simulating $250 deposits. Each thread produces inconsistent output. What causes those inconsistencies? Consider the following:
How does an inconsistency arise in NeedForSynchronizationDemo? Suppose the deposit thread executes ft.transName = "Deposit"; and then calls Thread.sleep(). At that point, the deposit thread surrenders control of the processor for the time period it must sleep, and the withdrawal
thread executes. Assume the deposit thread sleeps for 500 milliseconds (a randomly selected value, thanks to Math.random(), from the inclusive range 0 through 999 milliseconds; I explore Math and its random() method in a future article). During the deposit thread's sleep time, the withdrawal thread executes ft.transName = "Withdrawal";, sleeps for 50 milliseconds (the withdrawal thread's randomly selected sleep value), awakes, executes ft.amount = 250.0;, and executes System.out.println (ft.transName + " " + ft.amount);—all before the deposit thread awakes. As a result, the withdrawal thread prints Withdrawal 250.0, which is correct. When the deposit thread awakes, it executes ft.amount = 2000.0;, followed by System.out.println (ft.transName + " " + ft.amount);. This time, Withdrawal 2000.0 prints, which is not correct. Although the deposit thread previously assigned the "Deposit"'s reference to transName, that reference subsequently disappeared when the withdrawal thread assigned the "Withdrawal"'s reference to that shared variable. When the deposit thread awoke, it failed to restore the correct reference to transName, but continued its execution by assigning 2000.0 to amount. Although neither variable has an invalid value, the combined values of both variables represent an inconsistency. In this
case, their values represent an attempt to withdraw ,000.