0

I am trying to use ExecutorService in order to write to a file. However, when I execute this code, the execution goes to outFile.close(); before the execution is completed, which throws

java.io.IOException: Stream closed

How can I call outFile.close() only after all the task has been completed?

(PS: I have removed all try/catch blocks for code clarity.)

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 1; i <= 1000; i++) {
  final int counter = i;
  executor.execute(new Runnable() {
    @Override
    public void run() {
      outFile.write(wld.getWord(counter) + "successful");
      outFile.write("\n");
    }               
  });
}

outFile.close();
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
Dipendra Pokharel
  • 508
  • 1
  • 5
  • 15

1 Answers1

1

You shoud first wait for all the tasks to finish. Once you've submitted all the jobs, you may invoke executor.shutdown() and wait for all threads to finish using executor.awaitTermination().

Here's an example:

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 1; i <= 1000; i++) {
      final int counter = i;
      executor.execute(new Runnable() {
          @Override
          public void run() {
              outFile.write(wld.getWord(counter) + "successful");
              outFile.write("\n");
          }               
      });
}

executor.shutdown(); //shut down executor
executor.awaitTermination(60, TimeUnit.SECONDS); //waiting for 60 seconds

outFile.close(); //and then you may safely close the stream knowing that all the tasks have finished

Note: the main thread may wake up before all the jobs are finished, because of the timeout. You may increase that time or wait in a loop until isTerminated() condition is met:

executor.shutdown();
while (!executor.isTerminated()) {
    executor.awaitTermination(1, TimeUnit.SECONDS);
}
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
  • This is exactly what I wanted. However, I calculated the execution of time with and without executer service and I don't feel any difference. Should I not see improved execution when using ExecutorService? – Dipendra Pokharel Jul 22 '19 at 18:50
  • 1
    You will hardly notice any performance improvement in this case, because writing speed is limited by IO and OS features. – Pavel Smirnov Jul 22 '19 at 18:56