Title: Practical exercise 1 Discussion
1Practical exercise 1Discussion
- Threads in Java
- Mutual exclusion in Java
2The exercise
- Couriers deposit money in a bank.
- Each courier is a thread.
- Somehow, the total amount of money deposited
differed from the amount of money actually in the
bank. - Find the reasons for this and correct the problem!
3Diagnosis
- Some runs of the handed out program illustrates
the problems
gt java Bank 5 2000000 Starting simulation of 5
couriers with 2000000 deposits each. All couriers
are done. Money in the bank 933878146 Total
money deposited 994957883 Discrepancy
61079737 Elapsed time 3976 milliseconds.
gt java Bank 5 2000000 Starting simulation of 5
couriers with 2000000 deposits each. All couriers
are done. Money in the bank 994983480 Total
money deposited 994983346 Discrepancy
-134 Elapsed time 3885 milliseconds.
- The amount of money in the bank doesnt match the
amount of money actually deposited
4Diagnosis (cont.)
Courier
public class Bank .. add money to
Bank ..
public class Bank .. create Thread
courier ..
Courier 1
Bank
Courier 2
Courier 3
5Diagnosis (cont.)
public void courierDone() int moneyInBank
nightSafeAmount vaultAmount int
moneyDeposited calculateMoneyDeposited() Syste
m.out.println("Money in the bank
"moneyInBank) System.out.println("Total money
deposited"moneyDeposited) ..
public class Bank private int
nightSafeAmount private int vaultAmount ..
6Diagnosis (cont.)
- Where are shared varibles modified?
- public void depositMoney(int amount)
/ Deposit a given amount of money. The
money is put in the night safe. If there is
too much money in the night safe, all the
money is transferred to the vault. / public
void depositMoney(int amount)
nightSafeAmount amount if(nightSafeAmount
gt 200) // Transfer the money in the night
safe to the vault vaultAmount
nightSafeAmount nightSafeAmount 0
7Diagnosis (cont.)
- Synchronized critical code
- synchronized keyword
public synchronized void depositMoney(int amount)
.
8Suggestions
- Use mutual exclusion when needed
- How much synchronization?
- Even when a program contains only a single thread
running on a single processor, a synchronized
method call is still slower than an
unsynchronized method call - Questions?