Home Segments Top Top Previous Next

903: Sidetrip

To solve the interference problem illustrated in Segment 902, you need to ensure that the deposit method does not allow the withdraw method to run on the same bank-account instance before the deposit method has finished its work, even though both methods are under the control of independent threads.

To ensure that the two methods do not work on the same bank-account instance at the same time, you need only to mark both method definitions with the synchronized keyword:

public synchronized void deposit(int amount) { ... } 
public synchronized void withdraw(int amount) { ... } 

Such synchronized methods cannot run on the same bank-account instance at the same time, because Java has what is called a locking mechanism. Conceptually, each class instance has exactly one lock, and any synchronized method must have that lock to start. Once a synchronized method starts, it holds onto the lock until it has completed its work. Thus, no other synchronized method can run on that class instance during that time.