Practical exercise 1 Discussion - PowerPoint PPT Presentation

1 / 8
About This Presentation
Title:

Practical exercise 1 Discussion

Description:

Somehow, the total amount of money deposited differed from the amount of money ... a synchronized method call is still slower than an unsynchronized method call ... – PowerPoint PPT presentation

Number of Views:17
Avg rating:3.0/5.0
Slides: 9
Provided by: hienn8
Category:

less

Transcript and Presenter's Notes

Title: Practical exercise 1 Discussion


1
Practical exercise 1Discussion
  • Threads in Java
  • Mutual exclusion in Java

2
The 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!

3
Diagnosis
  • 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

4
Diagnosis (cont.)
  • Bank

Courier
public class Bank .. add money to
Bank ..
public class Bank .. create Thread
courier ..
Courier 1
Bank
Courier 2
Courier 3
5
Diagnosis (cont.)
  • Program Outputs

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) ..
  • Shared varible?

public class Bank private int
nightSafeAmount private int vaultAmount ..
6
Diagnosis (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

7
Diagnosis (cont.)
  • Synchronized critical code
  • synchronized keyword

public synchronized void depositMoney(int amount)
.
  • Re-run the program

8
Suggestions
  • 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?
Write a Comment
User Comments (0)
About PowerShow.com