forked from henri-tremblay/DeadlockLabJavaOne2012
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Symposium.java
51 lines (47 loc) · 1.64 KB
/
Symposium.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package eu.javaspecialists.deadlock.lab2;
import java.util.concurrent.*;
/**
* At the symposium, we create a bunch of thinkers and place cups of wine
* between them. We then run them in a cached thread pool. Unfortunately when
* all the Thinker instances try to drink at the same time, they cause a
* deadlock.
* <p/>
* DO NOT CHANGE THIS CODE!
*
* @author Heinz Kabutz
*/
public class Symposium {
private final Krasi[] cups;
private final Thinker[] thinkers;
public Symposium(int delegates) {
cups = new Krasi[delegates];
thinkers = new Thinker[delegates];
for (int i = 0; i < cups.length; i++) {
cups[i] = new Krasi();
}
for (int i = 0; i < delegates; i++) {
Krasi left = cups[i];
Krasi right = cups[(i + 1) % delegates];
thinkers[i] = new Thinker(i, left, right);
}
}
public void run() throws InterruptedException {
// do this after we created the symposium, so that we do not
// let the reference to the Symposium escape.
ExecutorService exec = Executors.newCachedThreadPool();
CompletionService<String> results =
new ExecutorCompletionService<String>(exec);
for (Thinker thinker : thinkers) {
results.submit(thinker);
}
System.out.println("Waiting for results");
for (@SuppressWarnings("unused") Thinker thinker : thinkers) {
try {
System.out.println(results.take().get());
} catch (ExecutionException e) {
e.getCause().printStackTrace();
}
}
exec.shutdown();
}
}