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(); 
0

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

2 Comments

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?
You will hardly notice any performance improvement in this case, because writing speed is limited by IO and OS features.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.