Saturday, April 1, 2017

Executor Service Example, for invoking multiple calls Parallelly

You may need to run a particular task (that can run independently) in parallel fashion in order to improve performance, or lets say, simulate a method call in multi-threaded environment:

Here is a example code snippet to do so:
//prepare task
Callable<String> callableTask = () -> {
callAMethodHere(); // do you execution here, write to file or call an exiting method etc.
return "Tasker";
};
List<Callable<String>> callableTasks = new ArrayList<>();
for(int counnt=0; count < 10 ; count++){
callableTasks.add( callableTask );
}
//prepare executor service
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<String>> futures = executorService.invokeAll(callableTasks);
executorService.shutdown();


No comments:

Post a Comment

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...