-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathExplicitConditionQueue.java
84 lines (77 loc) · 2.18 KB
/
ExplicitConditionQueue.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package br.com.leonardoz.patterns.condition_queues;
import java.util.UUID;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Pattern: Explicit Condition Queues
*
* Motivations: State dependent classes can be difficult to implement, mainly
* because some precondition states can become true through another thread.
* Condition Queues help us to identify the condition predicates and do control
* to programming flux associated with it. Also, wait/notify are based in
* intrinsic lock mechanisms.
*
* Intent: Create a Condition Queue mechanism based on the capabilities of the
* Lock interface to generate Conditions.
*
* Applicability: State dependent algorithms used in concurrent programming.
*
*/
public class ExplicitConditionQueue {
private static final int LIMIT = 5;
private int messageCount = 0;
private Lock lock = new ReentrantLock();
private Condition limitReachedCondition = lock.newCondition();
private Condition limitUnreachedCondition = lock.newCondition();
public void stopMessages() throws InterruptedException {
lock.lock();
try {
while (messageCount < LIMIT) {
limitReachedCondition.await();
}
System.err.println("Limit reached. Wait 2s");
Thread.sleep(2000);
messageCount = 0;
limitUnreachedCondition.signalAll();
} finally {
lock.unlock();
}
}
public void printMessages(String message) throws InterruptedException {
lock.lock();
try {
while (messageCount == LIMIT) {
limitUnreachedCondition.await();
}
System.out.println(message);
messageCount++;
limitReachedCondition.signalAll();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
var queue = new ExplicitConditionQueue();
// Will run indefinitely
new Thread(() -> {
while (true) {
var uuidMessage = UUID.randomUUID().toString();
try {
queue.printMessages(uuidMessage);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
while (true) {
try {
queue.stopMessages();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}