Home Segments Top Top Previous Next

902: Sidetrip

Multithreaded programs may require synchronization, which is a way of ensuring that two methods will not run at the same time with the same class instance as their target.

One classic example is that of bank-account deposits and withdrawals. If you have different threads call deposit and withdraw methods on the same bank-account instance, there is a chance that both methods will fetch the current balance from an instance variable before either method performs the appropriate addition or subtraction. Thus, one method may work on an out-of-date balance, as illustrated by the following event sequence, producible by two threads running deposit and withdraw methods on the same bank-account instance at the same time:

Deposit thread                          Withdraw thread 
--------------                          ---------------  
Fetch current balance, 100  

                                        Fetch current balance, 100 

Add 10 to 100, 
Write balance, 110  

                                        Subtract 10 from 100 
                                        Write balance, 90