One fool proof way (out of many) to execute any method in parallel is to start a thread pool and then assign tasks to it and wait for the tasks to finish.
public static ThreadPoolExecutor getExecutorService(int poolSize, int maxPoolSize{
int threadPoolshutDownTime = 10L;
ThreadPoolExecutor executorService= new ThreadPoolExecutor(poolSize, maxPoolSize, threadPoolshutDownTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
executorService.allowCoreThreadTimeOut(true); // allows the threadpool to shutdown if no task is assigned
return executorService;
}
Now call this inside your method like the following :
public void a(List<Object> list) throws InterruptedException, ExecutionException {
List<Callable<Boolean>> callables = new ArrayList<>(list.size());
list.forEach(object ->callables.add(() -> return asynchMethod(object)));
for (Future<Boolean> booleanFuture : this.getExecutorService(1,4).invokeAll(callables)) {
booleanFuture.get(); //this will wait for the callables to be done!
}
}
Also modify your aysncMethod as the following :
private boolean asynchMethod(Object o) {
return o.doMagic(); //doMagic returns a boolean when completed
}