I am learning how to use thread pools in Java using ExecutorService
, here is an example I am working on:
public class Example {
static class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.command;
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
// while (!executor.isTerminated()) {
// }
System.out.println("Finished all threads");
}
}
I have two questions:
How should I wait for the termination of an ExecutorService
, should I use awaitTermination()
or isTerminated()
(it has been suggested that the latter is a wrong way to do it)?
Are the Runnable
s correctly added to the executor or should I use submit()
together with a Future<T>
callback?
It probably depends on the context, so would you please explain (for both questions) when should I use each of the solutions mentioned.
Couple of ways to achieve it:
(a) Call awaitTermination(long someTime, TimeUnit ....)
inside while (!executor.isTerminated())
.
(b) Store all callable inside Collection object and call executor.invokeAll(....)
. This is going to wait till all task gets completed by executor service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With