Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to submit to and wait for termination of an ExecutorService

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:

  1. 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)?

  2. Are the Runnables 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.

like image 200
syntagma Avatar asked Oct 18 '22 15:10

syntagma


1 Answers

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.

like image 108
Java Guru Avatar answered Oct 21 '22 05:10

Java Guru