forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadSafeStack.java
More file actions
59 lines (45 loc) · 1.99 KB
/
Copy pathThreadSafeStack.java
File metadata and controls
59 lines (45 loc) · 1.99 KB
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
52
53
54
55
56
57
58
59
package modern.challenge;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class ThreadSafeStack {
private static final Logger logger = Logger.getLogger(ThreadSafeStack.class.getName());
// A ConcurrentLinkedDeque implementation can be used as a Stack (Last-In-First-Out)
// Switch to ArrayDeque to see how pop is trying to pop
// the same item in different threads because ArrayDeque is not thread-safe
// private static Deque<Integer> stack = new ArrayDeque<>();
private static Deque<Integer> stack = new ConcurrentLinkedDeque<>();
public static void main(String[] args) throws InterruptedException {
System.setProperty("java.util.logging.SimpleFormatter.format",
"[%1$tT] [%4$-7s] %5$s %n");
logger.info("Push ...");
// push values for 1 to 10 using a single thread
for (int i = 0; i < 10; i++) {
int item = i + 1;
logger.info(() -> "Produced: " + item
+ " by " + Thread.currentThread().getName());
stack.push(item);
}
logger.info("Pop ... ");
// pop values using 5 threads
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Integer item = stack.pop();
logger.info(() -> "Consumed: " + item
+ " by " + Thread.currentThread().getName());
});
}
executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
logger.info("All the threads have ended successfully");
}
}