Changed the implementation for better understanding

This commit is contained in:
Narendra Pathai
2015-07-27 15:29:56 +05:30
parent 4c22055e47
commit dc4904c8d0
5 changed files with 117 additions and 55 deletions
@@ -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);
}