mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-05-16 00:59:02 +00:00
Changed the implementation for better understanding
This commit is contained in:
+9
-23
@@ -1,7 +1,6 @@
|
||||
package com.iluwatar.halfsynchalfasync;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
@@ -12,40 +11,27 @@ import java.util.concurrent.ThreadPoolExecutor;
|
||||
* picks up the task and executes it in background and the result is posted back to the caller via
|
||||
* {@link Future}.
|
||||
*/
|
||||
public abstract class AsynchronousService<I, O> {
|
||||
public class AsynchronousService {
|
||||
|
||||
/*
|
||||
* This is the synchronous layer to which request to do work is submitted.
|
||||
* This is the synchronous layer to which request to do work is delegated.
|
||||
*/
|
||||
private SynchronousLayer syncLayer = new SynchronousLayer();
|
||||
private SynchronousLayer syncLayer;
|
||||
|
||||
public AsynchronousService(QueuingLayer queuingLayer) {
|
||||
this.syncLayer = new SynchronousLayer(queuingLayer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes arithmetic sum for n
|
||||
*
|
||||
* @return future representing arithmetic sum of n
|
||||
*/
|
||||
public Future<O> execute(final I input) {
|
||||
public void execute(final AsyncTask<?> task) {
|
||||
/*
|
||||
* This is the key part of this pattern where the caller thread does not block until
|
||||
* the result of work is computed but is delegated to the synchronous layer which
|
||||
* computes the task in background. This is useful if caller thread is an UI thread,
|
||||
* which MUST remain responsive to user inputs.
|
||||
*/
|
||||
return syncLayer.submit(new Callable<O>() {
|
||||
|
||||
@Override
|
||||
public O call() throws Exception {
|
||||
return doInBackground(input);
|
||||
}
|
||||
|
||||
});
|
||||
syncLayer.execute(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called in context of background thread where the implementation should compute
|
||||
* and return the result for input.
|
||||
*
|
||||
* @return computed result
|
||||
*/
|
||||
protected abstract O doInBackground(I input);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user