0

UPDATE: I Fixed it with this code(Works only if you know the total tasks count, My case)

int totalThreads = 0;
int finishedThreads = 0;

private void checkExecutorFinished() {
    if(finishedThreads == totalThreads) {
        // Exceutor threads got finished
        System.out.println(shufflingResult);
    }
}
private void startMappingPhase() throws Exception {
    totalThreads = fileLines.size();
    for (String line : fileLines) {
        Future future = new ExecutingController().mapping(line);
        while (!future.isDone()) {
            //
        }
        shuffle((Collection<Pair<String, Integer>>) future.get());
        finishedThreads++;
        checkExecutorFinished();
    }
}

UPDATE: My question is clear i need to do that by executor submit; not other methods

I'm using executor service to do my tasks, I want to be informed when it's threads get finished, I googled it found out there is a way but by calling executor execute since i'm using executor submit to add my tasks, I didn't find a way to do that so, Is there a way?

Ahmad B
  • 29
  • 1
  • 3

1 Answers1

3

executor.submit returns Future object, Future has many utility methods like isDone(), get() etc..!!

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html

Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90
  • I know there is a method isDone for the future but it just tell if that future was done, I need to know if others futures are done too :) – Ahmad B Jun 17 '19 at 23:15
  • @AhmadB If you're submitting your tasks all together, use [`invokeAll`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)). – Slaw Jun 17 '19 at 23:22
  • I know that too but i think it more slowly since i need to loop for futures result too, My question is clear :)) – Ahmad B Jun 17 '19 at 23:29
  • @AhmadB The time it takes to loop over the completed futures will be insignificant. If you want to do this through the `submit` methods you'll end up doing nearly the same thing anyway—putting the futures in a collection, looping over them, and calling `get` on each one. I don't understand, however, why using `invokeAll` is not acceptable. – Slaw Jun 17 '19 at 23:44
  • @Slaw I know it do the same job.. But I'm looking for a way with submit – Ahmad B Jun 17 '19 at 23:57
  • @AhmadB [This answer](https://stackoverflow.com/a/3269687/6395627) to the duplicate gives an example using `submit` (second code block). – Slaw Jun 18 '19 at 00:04
  • @Slaw I fixed it with a simple solution, Thanks for your time :) – Ahmad B Jun 18 '19 at 00:35