Concurrency and Mutex
Implementing synchronized access to shared resources.
Nathan Chen, Kevin Lin, with thanks to many others.
1
2
Give all possible outputs of the two concurrent threads
Q
public void thread1() {
String one = "A";
System.out.println(one);
String one = "B";
System.out.println("B");
}
public void thread2() {
System.out.println("C");
System.out.println("D");
}
Q1: Give all possible outputs of the two concurrent threads
Give all possible outputs of the two concurrent threads
3
A
Is the following code safe from concurrency issues?
4
private int balance = 150;
int getBalance() {
return balance;
}
void withdraw(int amount) {
if(amount > getBalance())
throw new WithdrawTooLargeException();
// maybe balance changed, so get the new balance
setBalance(getBalance() - amount);
}
Q
Q1: Is the following code safe from concurrency issues?
Is the following code safe from concurrency issues?
5
A
How many lock ops are needed to synchronize addIngredient?
6
Q
private Stack<String> smoothie = new Stack<>();
public String addIngredient(String ingredient) {
if (smoothie.size() >= MAX) throw new SmoothieSizeException();
if (ingredient.equals("banana")) {
return "I'm allergic, sorry.";
} else {
smoothie.push(ingredient);
return "Ingredient added!";
}
}
Q1: How many lock ops are needed to synchronize addIngredient?
How many lock ops are needed to synchronize addIngredient?
A
What is the most significant problem with swipeCard?
8
Q
private Password[] passwords = new Password[N];
private int diningDollars = 1000;
void swipeCard(int amount) {
synchronized(passwords[i]) {
if (amount % 5 == 0) passwords[i] = new Password();
int currentBalance = this.diningDollars;
this.diningDollars = currentBalance - amount;
}
}
Q1: What is the most significant problem with swipeCard?
What is the most significant problem with swipeCard?
A