package com.iluwatar.halfsynchalfasync; import java.util.concurrent.LinkedBlockingQueue; /** * * This application demonstrates Half-Sync/Half-Async pattern. Key parts of the pattern are * {@link AsyncTask} and {@link AsynchronousService}. * *
* PROBLEM
*
* A concurrent system have a mixture of short duration, mid duration and long duration tasks.
* Mid or long duration tasks should be performed asynchronously to meet quality of service
* requirements.
*
*
INTENT
*
* The intent of this pattern is to separate the the synchronous and asynchronous processing
* in the concurrent application by introducing two intercommunicating layers - one for sync
* and one for async. This simplifies the programming without unduly affecting the performance.
*
*
* APPLICABILITY
*
*
* IMPLEMENTATION
*
* The main method creates an asynchronous service which does not block the main thread while
* the task is being performed. The main thread continues its work which is similar to Async Method
* Invocation pattern. The difference between them is that there is a queuing layer between Asynchronous
* layer and synchronous layer, which allows for different communication patterns between both layers.
* Such as Priority Queue can be used as queuing layer to prioritize the way tasks are executed.
* Our implementation is just one simple way of implementing this pattern, there are many variants possible
* as described in its applications.
*
*/
public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main(String[] args) {
AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>());
/*
* A new task to calculate sum is received but as this is main thread, it should not block.
* So it passes it to the asynchronous task layer to compute and proceeds with handling other
* incoming requests. This is particularly useful when main thread is waiting on Socket to receive
* new incoming requests and does not wait for particular request to be completed before responding
* to new request.
*/
service.execute(new ArithmeticSumTask(1000));
/* New task received, lets pass that to async layer for computation. So both requests will be
* executed in parallel.
*/
service.execute(new ArithmeticSumTask(500));
service.execute(new ArithmeticSumTask(2000));
service.execute(new ArithmeticSumTask(1));
}
/**
*
* ArithmeticSumTask
*
*/
static class ArithmeticSumTask implements AsyncTask