Reputation: 763
I am very new to the Java concurrent package. I am using the java.util.concurrent.CompletionService class for getting the results from the pool without any waiting for the other threads to complete the task. But I was unable to get the tasks even after 10 min of code execution. I am just printing the thread name in the task. Here is my code.
public class CompletionService {
public void execute(ThreadPoolExecutor argThreadPoolExecutor)
throws InterruptedException, ExecutionException {
java.util.concurrent.CompletionService<String> completionService =
new ExecutorCompletionService<String>(argThreadPoolExecutor);
int counter = 0;
for (int i = 0; i < 4; i++) {
Task task = new Task();
completionService.submit(task);
++counter;
}
print(counter, completionService);
}
private void print(int argCounter,
java.util.concurrent.CompletionService<String> argCompletionService)
throws InterruptedException, ExecutionException {
String s = argCompletionService.take().get();
if (s != null && !s.isEmpty()) {
System.out.println(s);
}
}
public static void main(String[] args) throws InterruptedException,
ExecutionException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8, 8,
3000, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
CompletionService completionService = new CompletionService();
completionService.execute(threadPoolExecutor);
threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
}
Task class:
public class Task implements Callable<String> {
@Override
public String call() throws Exception {
String name = Thread.currentThread().getName();
return name;
}
}
Result: pool-1-thread-1
I am getting only one thread information. I waited 10-15 min still I am not getting the results. Am I wrong anywhere.? Can any one help me on this.?
Thanq.
Upvotes: 0
Views: 239
Reputation: 7555
You're not looping in your print(...)
method, so you're only ever taking the first result from the completion service. Try this instead:
private void print(int argCounter, CompletionService<String> argCompletionService) throws InterruptedException, ExecutionException {
for (int i = 0; i < argCounter; i++) {
String s = argCompletionService.take().get();
if (s != null && !s.isEmpty())
System.out.println(s);
}
}
Also you're not shutting down your ExecutorService
. This will mean that your program will never finish. Add a call to shutdown()
after your task submission loop.
Upvotes: 1
Reputation: 6306
completionService.execute(threadPoolExecutor);
threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
You will block here forever because you have not asked the ThreadPoolExecutor
to shutdown.
Upvotes: 3