Skip to content

Commit 175e9f5

Browse files
authored
Merge pull request iluwatar#537 from robertt240/master
guarded suspension pattern iluwatar#69
2 parents cca4760 + 449aed1 commit 175e9f5

File tree

9 files changed

+300
-1
lines changed

9 files changed

+300
-1
lines changed

guarded-suspension/README.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
layout: pattern
3+
title: Guarded Suspension
4+
folder: guarded-suspension
5+
permalink: /patterns/guarded-suspension/
6+
categories: Concurrency
7+
tags:
8+
- Java
9+
- Difficulty-Beginner
10+
---
11+
12+
## Intent
13+
Use Guarded suspension pattern to handle a situation when you want to execute a method on object which is not in a proper state.
14+
15+
![Guarded Suspension diagram](./etc/guarded-suspension.png)
16+
17+
## Applicability
18+
Use Guarded Suspension pattern when the developer knows that the method execution will be blocked for a finite period of time
19+
20+
## Related patterns
21+
* Balking
10.1 KB
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<class-diagram version="1.1.13" icons="true" automaticImage="JPEG" always-add-relationships="false"
3+
generalizations="true" realizations="true" associations="true" dependencies="false" nesting-relationships="true"
4+
router="FAN">
5+
<class id="1" language="java" name="com.iluwatar.guarded.suspension.GuardedQueue"
6+
project="java-design-patterns_guarded-suspension"
7+
file="/java-design-patterns_guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java"
8+
binary="false" corner="BOTTOM_RIGHT">
9+
<position height="277" width="326" x="301" y="172"/>
10+
<display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
11+
sort-features="false" accessors="true" visibility="true">
12+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
13+
<operations public="true" package="true" protected="true" private="true" static="true"/>
14+
</display>
15+
</class>
16+
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
17+
sort-features="false" accessors="true" visibility="true">
18+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
19+
<operations public="true" package="true" protected="true" private="true" static="true"/>
20+
</classifier-display>
21+
<association-display labels="true" multiplicity="true"/>
22+
</class-diagram>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
@startuml
2+
package com.iluwatar.guarded.suspension {
3+
class GuardedQueue {
4+
- LOGGER : Logger {static}
5+
- sourceList : Queue<Integer>
6+
+ GuardedQueue()
7+
+ get() : Integer
8+
+ put(e : Integer)
9+
}
10+
}
11+
@enduml

guarded-suspension/pom.xml

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
The MIT License
5+
Copyright (c) 2014 Ilkka Seppälä
6+
7+
Permission is hereby granted, free of charge, to any person obtaining a copy
8+
of this software and associated documentation files (the "Software"), to deal
9+
in the Software without restriction, including without limitation the rights
10+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
copies of the Software, and to permit persons to whom the Software is
12+
furnished to do so, subject to the following conditions:
13+
14+
The above copyright notice and this permission notice shall be included in
15+
all copies or substantial portions of the Software.
16+
17+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
THE SOFTWARE.
24+
25+
-->
26+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
27+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
28+
29+
<modelVersion>4.0.0</modelVersion>
30+
<parent>
31+
<groupId>com.iluwatar</groupId>
32+
<artifactId>java-design-patterns</artifactId>
33+
<version>1.15.0-SNAPSHOT</version>
34+
</parent>
35+
<packaging>jar</packaging>
36+
<artifactId>guarded-suspension</artifactId>
37+
<dependencies>
38+
<dependency>
39+
<groupId>junit</groupId>
40+
<artifactId>junit</artifactId>
41+
<scope>test</scope>
42+
</dependency>
43+
</dependencies>
44+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
/**
24+
* Guarded-suspension is a concurrent design pattern for handling situation when to execute some action we need
25+
* condition to be satisfied.
26+
* <p>
27+
* Implementation is based on GuardedQueue, which has two methods: get and put,
28+
* the condition is that we cannot get from empty queue so when thread attempt
29+
* to break the condition we invoke Object's wait method on him and when other thread put an element
30+
* to the queue he notify the waiting one that now he can get from queue.
31+
*/
32+
package com.iluwatar.guarded.suspension;
33+
34+
import java.util.concurrent.ExecutorService;
35+
import java.util.concurrent.Executors;
36+
import java.util.concurrent.TimeUnit;
37+
38+
/**
39+
* Created by robertt240 on 1/26/17.
40+
*/
41+
public class App {
42+
/**
43+
* Example pattern execution
44+
*
45+
* @param args - command line args
46+
*/
47+
public static void main(String[] args) {
48+
GuardedQueue guardedQueue = new GuardedQueue();
49+
ExecutorService executorService = Executors.newFixedThreadPool(3);
50+
51+
//here we create first thread which is supposed to get from guardedQueue
52+
executorService.execute(() -> {
53+
guardedQueue.get();
54+
}
55+
);
56+
57+
//here we wait two seconds to show that the thread which is trying to get from guardedQueue will be waiting
58+
try {
59+
Thread.sleep(2000);
60+
} catch (InterruptedException e) {
61+
e.printStackTrace();
62+
}
63+
//now we execute second thread which will put number to guardedQueue and notify first thread that it could get
64+
executorService.execute(() -> {
65+
guardedQueue.put(20);
66+
}
67+
);
68+
executorService.shutdown();
69+
try {
70+
executorService.awaitTermination(30, TimeUnit.SECONDS);
71+
} catch (InterruptedException e) {
72+
e.printStackTrace();
73+
}
74+
}
75+
76+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
* <p>
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
* <p>
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
* <p>
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.guarded.suspension;
24+
25+
import org.slf4j.Logger;
26+
import org.slf4j.LoggerFactory;
27+
28+
import java.util.LinkedList;
29+
import java.util.Queue;
30+
31+
32+
public class GuardedQueue {
33+
private static final Logger LOGGER = LoggerFactory.getLogger(GuardedQueue.class);
34+
private final Queue<Integer> sourceList;
35+
36+
public GuardedQueue() {
37+
this.sourceList = new LinkedList<>();
38+
}
39+
40+
/**
41+
* @return last element of a queue if queue is not empty
42+
*/
43+
public synchronized Integer get() {
44+
while (sourceList.isEmpty()) {
45+
try {
46+
LOGGER.info("waiting");
47+
wait();
48+
} catch (InterruptedException e) {
49+
e.printStackTrace();
50+
}
51+
}
52+
LOGGER.info("getting");
53+
return sourceList.peek();
54+
}
55+
56+
/**
57+
* @param e number which we want to put to our queue
58+
*/
59+
public synchronized void put(Integer e) {
60+
LOGGER.info("putting");
61+
sourceList.add(e);
62+
LOGGER.info("notifying");
63+
notify();
64+
}
65+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
* <p>
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
* <p>
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
* <p>
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.guarded.suspension;
24+
25+
import org.junit.Assert;
26+
import org.junit.Test;
27+
28+
import java.util.concurrent.ExecutorService;
29+
import java.util.concurrent.Executors;
30+
import java.util.concurrent.TimeUnit;
31+
32+
public class GuardedQueueTest {
33+
private volatile Integer value;
34+
35+
@Test
36+
public void testGet() {
37+
GuardedQueue g = new GuardedQueue();
38+
ExecutorService executorService = Executors.newFixedThreadPool(2);
39+
executorService.submit(() -> value = g.get());
40+
executorService.submit(() -> g.put(Integer.valueOf(10)));
41+
executorService.shutdown();
42+
try {
43+
executorService.awaitTermination(30, TimeUnit.SECONDS);
44+
} catch (InterruptedException e) {
45+
e.printStackTrace();
46+
}
47+
Assert.assertEquals(Integer.valueOf(10), value);
48+
}
49+
50+
@Test
51+
public void testPut() {
52+
GuardedQueue g = new GuardedQueue();
53+
g.put(12);
54+
Assert.assertEquals(Integer.valueOf(12), g.get());
55+
56+
}
57+
58+
}

pom.xml

+3-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@
121121
<module>factory-kit</module>
122122
<module>feature-toggle</module>
123123
<module>value-object</module>
124-
<module>module</module>
124+
<module>module</module>
125125
<module>monad</module>
126126
<module>mute-idiom</module>
127127
<module>mutex</module>
@@ -134,6 +134,8 @@
134134
<module>event-asynchronous</module>
135135
<module>queue-load-leveling</module>
136136
<module>object-mother</module>
137+
<module>guarded-suspension</module>
138+
137139
</modules>
138140

139141
<dependencyManagement>

0 commit comments

Comments
 (0)