forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadSafeQueue.java
More file actions
66 lines (53 loc) · 2.29 KB
/
ThreadSafeQueue.java
File metadata and controls
66 lines (53 loc) · 2.29 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
60
61
62
63
64
65
66
package modern.challenge;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
public class ThreadSafeQueue {
private static final Logger logger = Logger.getLogger(ThreadSafeQueue.class.getName());
// Switch to ArrayDeque to see how the same item is consumed multiple times.
// Since poll() retrieves and removes the head of this queue this should not happen.
// private static final Deque<Integer> queue = new ArrayDeque<>(10000);
private static final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10000);
private static final AtomicInteger itemNr = new AtomicInteger();
private static final Producer producer = new Producer();
private static final Consumer consumer = new Consumer();
private static ExecutorService producerService
= Executors.newFixedThreadPool(3);
private static ExecutorService consumerService
= Executors.newFixedThreadPool(3);
private static class Producer implements Runnable {
@Override
public void run() {
while (true) {
int item = itemNr.incrementAndGet();
queue.add(item);
logger.info(() -> "Produced: " + item
+ " by " + Thread.currentThread().getName());
}
}
}
private static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
Integer item = queue.poll();
if (item != null) {
logger.info(() -> "Consumed: " + item
+ " by " + Thread.currentThread().getName());
}
}
}
}
public static void main(String[] args) throws InterruptedException {
System.setProperty("java.util.logging.SimpleFormatter.format",
"[%1$tT] [%4$-7s] %5$s %n");
for (int i = 0; i < 3; i++) {
producerService.execute(producer);
consumerService.execute(consumer);
}
// since the producer and consumer run in a while(true) the application must be stopped manually
}
}