01: import java.util.concurrent.locks.Lock;
02: import java.util.concurrent.locks.ReentrantLock;
03: 
04: /**
05:    A bank account has a balance that can be changed by 
06:    deposits and withdrawals.
07: */
08: public class BankAccount
09: {  
10:    /**
11:       Constructs a bank account with a zero balance.
12:    */
13:    public BankAccount()
14:    {   
15:       balance = 0;
16:       balanceChangeLock = new ReentrantLock();
17:    }
18: 
19:    /**
20:       Constructs a bank account with a given balance.
21:       @param initialBalance the initial balance
22:    */
23:    public BankAccount(double initialBalance)
24:    {   
25:       balance = initialBalance;
26:    }
27: 
28:    /**
29:       Deposits money into the bank account.
30:       @param amount the amount to deposit
31:    */
32:    public void deposit(double amount)
33:    {  
34:       balanceChangeLock.lock();
35:       try
36:       {
37:          double newBalance = balance + amount;
38:          balance = newBalance;
39:       }
40:       finally
41:       {
42:          balanceChangeLock.unlock();
43:       }
44:    }
45: 
46:    /**
47:       Withdraws money from the bank account.
48:       @param amount the amount to withdraw
49:    */
50:    public void withdraw(double amount)
51:    {   
52:       balanceChangeLock.lock();
53:       try
54:       {
55:          double newBalance = balance - amount;
56:          balance = newBalance;
57:       }
58:       finally
59:       {
60:          balanceChangeLock.unlock();
61:       }
62:    }
63: 
64:    /**
65:       Gets the current balance of the bank account.
66:       @return the current balance
67:    */
68:    public double getBalance()
69:    {   
70:       return balance;
71:    }
72: 
73:    private double balance;
74:    private Lock balanceChangeLock;
75: }
76: