shutdown and awaitTermination which first call have any difference?

前端 未结 9 1187
渐次进展
渐次进展 2020-12-12 14:44

What is the difference between

ExecutorService eService = Executors.newFixedThreadPool(2);
eService.execute(new TestThread6());
eService.execute(new TestThre         


        
相关标签:
9条回答
  • 2020-12-12 15:06

    You need to call shutdownNow() method after the awaitTermination() method call happened. Then only you can find out the actual usage of awaitTermination() method.

    0 讨论(0)
  • 2020-12-12 15:10

    From Java8 ThreadPool awaitTermination method:

        try {
            for (;;) {
                if (runStateAtLeast(ctl.get(), TERMINATED))
                    return true;
                if (nanos <= 0)
                    return false;
                nanos = termination.awaitNanos(nanos);
            }
        } finally {
            mainLock.unlock();
        }
    

    It will first check run state of thread pool. And if the thread pool is not shut down(which set run state to terminated), awaitTermination method will not return until timeout. This explains why await a long time if you await first then shutdown.

    0 讨论(0)
  • 2020-12-12 15:11

    Main Difference

    shutdown()-

    1. Doesn't block the calling a thread i.e. the thread who called the shutdown().
    2. Excecutor doesn't accept any new task after calling shutdown().
    

    awaitTermination() -

    1. Blocks the calling thread. (as join() method do)
    

    Point of Confusion:- If shutdown() does not kill the previously submitted tasks, why do we need awaitTermination()?

    awaitTermination means waiting for the tasks to be completed/terminated, right? shutdown() is doing the same- waiting for any task which is already submitted along with the running tasks to continue till completed/terminated, then why another method awaitTermination(..)? Below is the explanation:

    Suppose you can wait for 10 min only to complete all the task that are submitted and after that want to call shutdownNow()(---you already know what it do) then use awaitTermination(long timeout, TimeUnit unit) after calling shutdown().

    Notice the method arguments in awaitTermination(long timeout, TimeUnit unit). This timeout is the key here.

    If there is no time restriction, shutdown() is OK. No need of awaitTermination().

    0 讨论(0)
提交回复
热议问题