Java Reference
In-Depth Information
42
// data-corruption problem and make it easy to see.
43
try {
44
Thread.sleep( 5 );
45 }
46 catch (InterruptedException ex) {
47 }
48
49 balance = newBalance;
50 }
51 }
52 }
The classes AddAPennyTask and Account in lines 24-51 are inner classes. Line 4 creates
an Account with initial balance 0 . Line 11 creates a task to add a penny to the account and
submits the task to the executor. Line 11 is repeated 100 times in lines 10-12. The program
repeatedly checks whether all tasks are completed in lines 17 and 18. The account balance is
displayed in line 20 after all tasks are completed.
The program creates 100 threads executed in a thread pool executor (lines 10-12). The
isTerminated() method (line 17) is used to test whether the thread is terminated.
The balance of the account is initially 0 (line 32). When all the threads are finished, the bal-
ance should be 100 but the output is unpredictable. As can be seen in Figure 30.10, the answers
are wrong in the sample run. This demonstrates the data-corruption problem that occurs when
all the threads have access to the same data source simultaneously.
F IGURE 30.10
The AccountWithoutSync program causes data inconsistency.
Lines 39-49 could be replaced by one statement:
balance = balance + amount;
It is highly unlikely, although plausible, that the problem can be replicated using this single
statement. The statements in lines 39-49 are deliberately designed to magnify the data-
corruption problem and make it easy to see. If you run the program several times but still
do not see the problem, increase the sleep time in line 44. This will increase the chances for
showing the problem of data inconsistency.
What, then, caused the error in this program? A possible scenario is shown in Figure 30.11.
Step
Balance
Task 1
Task 2
1
0
newBalance = balance + 1 ;
2
0
newBalance = balance + 1 ;
3
1
balance = newBalance;
4
1
balance = newBalance;
F IGURE 30.11
Task 1 and Task 2 both add 1 to the same balance.
 
 
Search WWH ::




Custom Search