Skip to content

Commit 8e846c3

Browse files
committed
Merge pull request iluwatar#177 from npathai/HalfSyncHalfAsync
Half sync half async
2 parents 2aa9681 + 64ce186 commit 8e846c3

File tree

9 files changed

+363
-1
lines changed

9 files changed

+363
-1
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ Concurrency patterns are those types of design patterns that deal with the multi
7272
* [Double Checked Locking](#double-checked-locking)
7373
* [Thread Pool](#thread-pool)
7474
* [Async Method Invocation](#async-method-invocation)
75+
* [Half-Sync/Half-Async](#half-sync-half-async)
7576

7677
### Presentation Tier Patterns
7778

@@ -714,7 +715,22 @@ validation and for building to order
714715
* you want to orchestrate calls to multiple business services
715716
* you want to encapsulate service lookups and service calls
716717

718+
## <a name="half-sync-half-async">Half-Sync/Half-Async</a> [&#8593;](#list-of-design-patterns)
719+
**Intent:** The Half-Sync/Half-Async pattern decouples synchronous I/O from asynchronous I/O in a system to simplify concurrent programming effort without degrading execution efficiency.
717720

721+
![Half-Sync/Half-Async class diagram](./half-sync-half-async/etc/half-sync-half-async.png)
722+
723+
**Applicability:** Use Half-Sync/Half-Async pattern when
724+
* A system possesses following characteristics:
725+
* System must perform tasks in response to external events that occur asynchronously, like hardware interrupts in OS
726+
* It is inefficient to dedicate separate thread of control to perform synchronous I/O for each external source of event
727+
* The higher level tasks in the system can be simplified significantly if I/O is performed synchronously.
728+
* One or more tasks in a system must run in a single thread of control, while other tasks may benefit from multi-threading.
729+
730+
**Real world examples:**
731+
* [BSD Unix networking subsystem](http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf)
732+
* [Real Time CORBA](http://www.omg.org/news/meetings/workshops/presentations/realtime2001/4-3_Pyarali_thread-pool.pdf)
733+
* [Android AsyncTask framework](http://developer.android.com/reference/android/os/AsyncTask.html)
718734

719735
# Frequently asked questions
720736

32.1 KB
Loading
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
3+
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
4+
<class id="1" language="java" name="com.iluwatar.halfsynchalfasync.AsynchronousService" project="half-sync-half-async"
5+
file="/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsynchronousService.java" binary="false"
6+
corner="BOTTOM_RIGHT">
7+
<position height="115" width="265" x="41" y="37"/>
8+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
9+
sort-features="false" accessors="true" visibility="true">
10+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
11+
<operations public="true" package="true" protected="true" private="true" static="true"/>
12+
</display>
13+
</class>
14+
<interface id="2" language="java" name="com.iluwatar.halfsynchalfasync.AsyncTask" project="half-sync-half-async"
15+
file="/half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync/AsyncTask.java" binary="false"
16+
corner="BOTTOM_RIGHT">
17+
<position height="-1" width="-1" x="776" y="223"/>
18+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
19+
sort-features="false" accessors="true" visibility="true">
20+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
21+
<operations public="true" package="true" protected="true" private="true" static="true"/>
22+
</display>
23+
</interface>
24+
<interface id="3" language="java" name="java.util.concurrent.BlockingQueue" project="async-method-invocation"
25+
file="/opt/Softwares/Eclipses/MARS/eclipse/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
26+
<position height="-1" width="-1" x="494" y="310"/>
27+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
28+
sort-features="false" accessors="true" visibility="true">
29+
<attributes public="false" package="false" protected="false" private="false" static="true"/>
30+
<operations public="false" package="false" protected="false" private="false" static="true"/>
31+
</display>
32+
</interface>
33+
<class id="4" language="java" name="java.util.concurrent.ThreadPoolExecutor" project="async-method-invocation"
34+
file="/opt/Softwares/Eclipses/MARS/eclipse/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
35+
<position height="-1" width="-1" x="174" y="343"/>
36+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
37+
sort-features="false" accessors="true" visibility="true">
38+
<attributes public="true" package="true" protected="true" private="false" static="true"/>
39+
<operations public="false" package="false" protected="false" private="false" static="false"/>
40+
</display>
41+
</class>
42+
<interface id="5" language="java" name="java.util.concurrent.Callable" project="async-method-invocation"
43+
file="/opt/Softwares/Eclipses/MARS/eclipse/jre/lib/rt.jar" binary="true" corner="BOTTOM_RIGHT">
44+
<position height="-1" width="-1" x="772" y="47"/>
45+
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
46+
sort-features="false" accessors="true" visibility="true">
47+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
48+
<operations public="true" package="true" protected="true" private="true" static="true"/>
49+
</display>
50+
</interface>
51+
<generalization id="6">
52+
<end type="SOURCE" refId="2"/>
53+
<end type="TARGET" refId="5"/>
54+
</generalization>
55+
<association id="7">
56+
<end type="SOURCE" refId="4" navigable="false">
57+
<attribute id="8" name="workQueue"/>
58+
<multiplicity id="9" minimum="0" maximum="1"/>
59+
</end>
60+
<end type="TARGET" refId="3" navigable="true"/>
61+
<display labels="true" multiplicity="true"/>
62+
</association>
63+
<dependency id="10">
64+
<end type="SOURCE" refId="1"/>
65+
<end type="TARGET" refId="3"/>
66+
</dependency>
67+
<dependency id="11">
68+
<end type="SOURCE" refId="1"/>
69+
<end type="TARGET" refId="4"/>
70+
</dependency>
71+
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
72+
sort-features="false" accessors="true" visibility="true">
73+
<attributes public="true" package="true" protected="true" private="true" static="true"/>
74+
<operations public="true" package="true" protected="true" private="true" static="true"/>
75+
</classifier-display>
76+
<association-display labels="true" multiplicity="true"/>
77+
</class-diagram>

half-sync-half-async/pom.xml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?xml version="1.0"?>
2+
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>com.iluwatar</groupId>
7+
<artifactId>java-design-patterns</artifactId>
8+
<version>1.5.0</version>
9+
</parent>
10+
<artifactId>half-sync-half-async</artifactId>
11+
<dependencies>
12+
<dependency>
13+
<groupId>junit</groupId>
14+
<artifactId>junit</artifactId>
15+
<scope>test</scope>
16+
</dependency>
17+
</dependencies>
18+
</project>
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package com.iluwatar.halfsynchalfasync;
2+
3+
import java.util.concurrent.LinkedBlockingQueue;
4+
5+
/**
6+
* This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are
7+
* {@link AsyncTask} and {@link AsynchronousService}.
8+
*
9+
* <p>
10+
* <i>PROBLEM</i>
11+
* <br/>
12+
* A concurrent system have a mixture of short duration, mid duration and long duration tasks.
13+
* Mid or long duration tasks should be performed asynchronously to meet quality of service
14+
* requirements.
15+
*
16+
* <p><i>INTENT</i>
17+
* <br/>
18+
* The intent of this pattern is to separate the the synchronous and asynchronous processing
19+
* in the concurrent application by introducing two intercommunicating layers - one for sync
20+
* and one for async. This simplifies the programming without unduly affecting the performance.
21+
*
22+
* <p>
23+
* <i>APPLICABILITY</i>
24+
* <br/>
25+
* <ul>
26+
* <li>UNIX network subsystems - In operating systems network operations are carried out
27+
* asynchronously with help of hardware level interrupts.</li>
28+
* <li>CORBA - At the asynchronous layer one thread is associated with each socket that is
29+
* connected to the client. Thread blocks waiting for CORBA requests from the client. On receiving
30+
* request it is inserted in the queuing layer which is then picked up by synchronous layer which
31+
* processes the request and sends response back to the client.</li>
32+
* <li>Android AsyncTask framework - Framework provides a way to execute long running blocking calls,
33+
* such as downloading a file, in background threads so that the UI thread remains free to respond
34+
* to user inputs.</i>
35+
* </ul>
36+
*
37+
* <p>
38+
* <i>IMPLEMENTATION</i>
39+
* <br/>
40+
* The main method creates an asynchronous service which does not block the main thread while
41+
* the task is being performed. The main thread continues its work which is similar to Async Method
42+
* Invocation pattern. The difference between them is that there is a queuing layer between Asynchronous
43+
* layer and synchronous layer, which allows for different communication patterns between both layers.
44+
* Such as Priority Queue can be used as queuing layer to prioritize the way tasks are executed.
45+
* Our implementation is just one simple way of implementing this pattern, there are many variants possible
46+
* as described in its applications.
47+
*/
48+
public class App {
49+
50+
public static void main(String[] args) {
51+
AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>());
52+
/*
53+
* A new task to calculate sum is received but as this is main thread, it should not block.
54+
* So it passes it to the asynchronous task layer to compute and proceeds with handling other
55+
* incoming requests. This is particularly useful when main thread is waiting on Socket to receive
56+
* new incoming requests and does not wait for particular request to be completed before responding
57+
* to new request.
58+
*/
59+
service.execute(new ArithmeticSumTask(1000));
60+
61+
/* New task received, lets pass that to async layer for computation. So both requests will be
62+
* executed in parallel.
63+
*/
64+
service.execute(new ArithmeticSumTask(500));
65+
service.execute(new ArithmeticSumTask(2000));
66+
service.execute(new ArithmeticSumTask(1));
67+
}
68+
69+
static class ArithmeticSumTask implements AsyncTask<Long> {
70+
private long n;
71+
72+
public ArithmeticSumTask(long n) {
73+
this.n = n;
74+
}
75+
76+
/*
77+
* This is the long running task that is performed in background. In our example
78+
* the long running task is calculating arithmetic sum with artificial delay.
79+
*/
80+
@Override
81+
public Long call() throws Exception {
82+
return ap(n);
83+
}
84+
85+
/*
86+
* This will be called in context of the main thread where some validations can be
87+
* done regarding the inputs. Such as it must be greater than 0. It's a small
88+
* computation which can be performed in main thread. If we did validated the input
89+
* in background thread then we pay the cost of context switching
90+
* which is much more than validating it in main thread.
91+
*/
92+
@Override
93+
public void onPreCall() {
94+
if (n < 0) {
95+
throw new IllegalArgumentException("n is less than 0");
96+
}
97+
}
98+
99+
@Override
100+
public void onPostCall(Long result) {
101+
// Handle the result of computation
102+
System.out.println(result);
103+
}
104+
105+
@Override
106+
public void onError(Throwable throwable) {
107+
throw new IllegalStateException("Should not occur");
108+
}
109+
}
110+
111+
private static long ap(long i) {
112+
try {
113+
Thread.sleep(i);
114+
} catch (InterruptedException e) {
115+
}
116+
return (i) * (i + 1) / 2;
117+
}
118+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.iluwatar.halfsynchalfasync;
2+
3+
import java.util.concurrent.Callable;
4+
5+
/**
6+
* Represents some computation that is performed asynchronously and its result.
7+
* The computation is typically done is background threads and the result is posted
8+
* back in form of callback. The callback does not implement {@code isComplete}, {@code cancel}
9+
* as it is out of scope of this pattern.
10+
*
11+
* @param <O> type of result
12+
*/
13+
public interface AsyncTask<O> extends Callable<O> {
14+
/**
15+
* Is called in context of caller thread before call to {@link #call()}. Large
16+
* tasks should not be performed in this method as it will block the caller thread.
17+
* Small tasks such as validations can be performed here so that the performance penalty
18+
* of context switching is not incurred in case of invalid requests.
19+
*/
20+
void onPreCall();
21+
22+
/**
23+
* A callback called after the result is successfully computed by {@link #call()}. In our
24+
* implementation this method is called in context of background thread but in some variants,
25+
* such as Android where only UI thread can change the state of UI widgets, this method is called
26+
* in context of UI thread.
27+
*/
28+
void onPostCall(O result);
29+
30+
/**
31+
* A callback called if computing the task resulted in some exception. This method
32+
* is called when either of {@link #call()} or {@link #onPreCall()} throw any exception.
33+
*
34+
* @param throwable error cause
35+
*/
36+
void onError(Throwable throwable);
37+
38+
/**
39+
* This is where the computation of task should reside. This method is called in context
40+
* of background thread.
41+
*/
42+
@Override
43+
O call() throws Exception;
44+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.iluwatar.halfsynchalfasync;
2+
3+
import java.util.concurrent.BlockingQueue;
4+
import java.util.concurrent.ExecutionException;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.FutureTask;
7+
import java.util.concurrent.ThreadPoolExecutor;
8+
import java.util.concurrent.TimeUnit;
9+
10+
/**
11+
* This is the asynchronous layer which does not block when a new request arrives. It just passes
12+
* the request to the synchronous layer which consists of a queue i.e. a {@link BlockingQueue} and
13+
* a pool of threads i.e. {@link ThreadPoolExecutor}. Out of this pool of worker threads one of the
14+
* thread picks up the task and executes it synchronously in background and the result is posted back
15+
* to the caller via callback.
16+
*/
17+
public class AsynchronousService {
18+
19+
/*
20+
* This represents the queuing layer as well as synchronous layer of the pattern. The thread
21+
* pool contains worker threads which execute the tasks in blocking/synchronous manner. Long
22+
* running tasks should be performed in the background which does not affect the performance of
23+
* main thread.
24+
*/
25+
private ExecutorService service;
26+
27+
/**
28+
* Creates an asynchronous service using {@code workQueue} as communication channel between
29+
* asynchronous layer and synchronous layer. Different types of queues such as Priority queue,
30+
* can be used to control the pattern of communication between the layers.
31+
*/
32+
public AsynchronousService(BlockingQueue<Runnable> workQueue) {
33+
service = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, workQueue);
34+
}
35+
36+
37+
/**
38+
* A non-blocking method which performs the task provided in background and returns immediately.
39+
* <p>
40+
* On successful completion of task the result is posted back using callback method
41+
* {@link AsyncTask#onPostCall(Object)}, if task execution is unable to complete normally
42+
* due to some exception then the reason for error is posted back using callback method
43+
* {@link AsyncTask#onError(Throwable)}.
44+
* <p>
45+
* NOTE: The results are posted back in the context of background thread in this implementation.
46+
*/
47+
public <T> void execute(final AsyncTask<T> task) {
48+
try {
49+
// some small tasks such as validation can be performed here.
50+
task.onPreCall();
51+
} catch (Exception e) {
52+
task.onError(e);
53+
}
54+
55+
service.submit(new FutureTask<T>(task) {
56+
@Override
57+
protected void done() {
58+
super.done();
59+
try {
60+
/* called in context of background thread. There is other variant possible
61+
* where result is posted back and sits in the queue of caller thread which
62+
* then picks it up for processing. An example of such a system is Android OS,
63+
* where the UI elements can only be updated using UI thread. So result must be
64+
* posted back in UI thread.
65+
*/
66+
task.onPostCall(get());
67+
} catch (InterruptedException e) {
68+
// should not occur
69+
} catch (ExecutionException e) {
70+
task.onError(e.getCause());
71+
}
72+
}
73+
});
74+
}
75+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.iluwatar.halfsynchalfasync;
2+
3+
import java.util.concurrent.ExecutionException;
4+
5+
import org.junit.Test;
6+
7+
public class AppTest {
8+
9+
@Test
10+
public void test() throws InterruptedException, ExecutionException {
11+
App.main(null);
12+
}
13+
}

pom.xml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@
7171
<module>front-controller</module>
7272
<module>repository</module>
7373
<module>async-method-invocation</module>
74-
<module>business-delegate</module>
74+
<module>business-delegate</module>
75+
<module>half-sync-half-async</module>
7576
</modules>
7677

7778
<dependencyManagement>

0 commit comments

Comments
 (0)