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
59 lines (44 loc) · 1.84 KB
/
ThreadSafeQueue.java
File metadata and controls
59 lines (44 loc) · 1.84 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.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class ThreadSafeQueue {
private static final Logger logger = Logger.getLogger(ThreadSafeQueue.class.getName());
private static final BlockingQueue<String> queue = new SynchronousQueue<>();
public static void main(String[] args) throws InterruptedException {
System.setProperty("java.util.logging.SimpleFormatter.format",
"[%1$tT] [%4$-7s] %5$s %n");
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
try {
String item = queue.take();
logger.info(() -> "Consumed: " + item
+ " by " + Thread.currentThread().getName());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
});
logger.info("Sleep 5 seconds ...");
// take a sleep
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
logger.info("Enqueue ...");
// only this will be enqueue, since there is a single consumer waiting
queue.offer("Rafael Nadal");
// the following two will not be enqueue
queue.offer("Roger Federer");
queue.offer("David Ferer");
logger.info("Done ...");
// this will return 0
logger.info(() -> "Queue size: " + queue.size());
executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
logger.info("All the threads have ended successfully");
}
}