Hello. I have some problem with CompletionService. My task: to parse parallely for about 300 html pages, i need to wait for all the results only for 5 seconds, then - return the result to main code. I`ve decided to use CompletionService + Callable for this. The question is how to stop all threads, that were caused by CompletionService and return the result from that pages, that were successfully parsed? In this code removed printlines, but i can say that 5 seconds is enough(there are good results, but program wait when all threads will be completed). My code performed about 2 minutes.
My calling code:
Collection<Callable<HCard>> solvers = new ArrayList<Callable<HCard>>();
for (final String currentUrl : allUrls) {
solvers.add(new Callable<HCard>() {
public HCard call() throws ParserException {
HCard hCard = HCardParser.parseOne(currentUrl);
if (hCard != null) {
return hCard;
} else {
return null;
}
}
});
}
ExecutorService execService = Executors.newCachedThreadPool();
Helper helper = new Helper();
List<HCard> result = helper.solve(execService, solvers);
//then i do smth with result list
My called code:
public class Helper {
List<HCard> solve(Executor e, Collection<Callable<HCard>> solvers) throws InterruptedException {
CompletionService<HCard> cs = new ExecutorCompletionService<HCard>(e);
int n = solvers.size();
Future<HCard> future = null;
HCard hCard = null;
ArrayList<HCard> result = new ArrayList<HCard>();
for (Callable<HCard> s : solvers) {
cs.submit(s);
}
for (int i = 0; i < n; ++i) {
try {
future = cs.take();
hCard = future.get();
if (hCard != null) {
result.add(hCard);
}
} catch (ExecutionException e1) {
future.cancel(true);
}
}
return result;
}
I attempted to use:
- awaitTermination(5000, TimeUnit.MILLISECONDS)
- future.cancel(true)
- execService.shutdownNow()
- future.get(5000, TimeUnit.MILLISECONDS);
- TimeOutException: i can`t get TimeOutException.
Please, help me on context of my code.
Thanks in advance!