Skip to content

Instantly share code, notes, and snippets.

@abhi2495
Last active July 19, 2020 20:30
Show Gist options
  • Save abhi2495/239d9781fc7ac9d673d1e329ea2bd801 to your computer and use it in GitHub Desktop.
Save abhi2495/239d9781fc7ac9d673d1e329ea2bd801 to your computer and use it in GitHub Desktop.

A demo Java code using ExecutorService to perform two tasks in parallel and then return after both finish

/*
##################################################################################
##################################################################################
######### IF YOU FOUND THIS GIST USEFUL, PLEASE LEAVE A STAR. THANKS. ############
##################################################################################
##################################################################################
*/
public void caller(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
Collection<Callable<Void>> callables = new ArrayList<>();
callables.add(() -> doTask1());
callables.add(() -> doTask2());
try {
List<Future<Void>> taskFutureList = executorService.invokeAll(callables);
taskFutureList.get(0).get();
taskFutureList.get(1).get();
} catch (InterruptedException | ExecutionException e) {
//error
}
}
public Void doTask1() {
//some logic
return null;
}
public Void doTask2() {
//some logic
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment