Executor Completion Service
Scenario: you want to load the tasks in parallel and then wait for the completion of all the tasks.
//Callable is different from Runnable that it returns result
private final class StringTask extends Callable<String>{
public String call(){
//Long operations
return "Run";
}
}
ExecutorService threadPool = Executors.newFixedThreadPool(4);
CompletionService<String> pool = new ExecutorCompletionService<String>(threadPool);
for(int i = 0; i < 10; i++){
pool.submit(new StringTask());
}
//you have the result in the order they are completed and you don’t have to keep a
//collection of Future
for(int i = 0; i < 10; i++){
String result = pool.take().get();
//Compute the result
}
threadPool.shutdown();
See: Java Concurrency: Executors and Thread Pools
No comments:
Post a Comment