@@ -15,6 +15,78 @@ Use Guarded suspension pattern to handle a situation when you want to execute a
1515## Applicability
1616Use Guarded Suspension pattern when the developer knows that the method execution will be blocked for a finite period of time
1717
18+ ## Explanation
19+
20+ Real world example
21+
22+ > When we reserve a dining room online and arrive to find it unready, the manager has it cleaned while we wait.
23+ > Once ready, we're escorted to the room. This process exemplifies the Guarded Suspension pattern.
24+
25+ In plain words
26+
27+ > Guarded Suspension pattern is used when one thread waits for the result of another thread's execution.
28+
29+ Wikipedia says
30+
31+ > In concurrent programming, Guarded Suspension manages operations requiring a lock
32+ > and a precondition, delaying execution until the precondition is met.
33+
34+ ** Programmatic Example**
35+
36+ The ` GuardedQueue ` class encapsulates a queue, and provides two synchronized methods, ` get ` and ` put ` .
37+ The ` get ` method waits if the queue is empty, and the ` put ` method adds an item to the queue and notifies waiting threads:
38+
39+ ``` java
40+ public class GuardedQueue {
41+ private final Queue<Integer > sourceList = new LinkedList<> ();
42+
43+ public synchronized Integer get () {
44+ while (sourceList. isEmpty()) {
45+ try {
46+ wait();
47+ } catch (InterruptedException e) {
48+ e. printStackTrace();
49+ }
50+ }
51+ return sourceList. peek();
52+ }
53+
54+ public synchronized void put (Integer e ) {
55+ sourceList. add(e);
56+ notify();
57+ }
58+ }
59+
60+ public class App {
61+ public static void main (String [] args ) {
62+ GuardedQueue guardedQueue = new GuardedQueue ();
63+ ExecutorService executorService = Executors . newFixedThreadPool(3 );
64+
65+ // Here we create the first thread which is supposed to get from guardedQueue
66+ executorService. execute(guardedQueue:: get);
67+
68+ try {
69+ Thread . sleep(2000 );
70+ } catch (InterruptedException e) {
71+ e. printStackTrace();
72+ }
73+
74+ // Here we create the second thread which is supposed to put to guardedQueue
75+ executorService. execute(() - > {
76+ guardedQueue. put(20 );
77+ });
78+
79+ executorService. shutdown();
80+ try {
81+ executorService. awaitTermination(30 , TimeUnit . SECONDS );
82+ } catch (InterruptedException e) {
83+ e. printStackTrace();
84+ }
85+ }
86+ }
87+ ```
88+
89+
1890## Related patterns
1991
2092* Balking
0 commit comments