ThreadPoolExecutor shutdown API doc verbiage "does not wait"

Nathan Hughes :

In the documentation for ThreadPoolExector#shutdown it says:

This method does not wait for previously submitted tasks to complete execution

What does that mean?

Because I would take it to mean that queued tasks that have been submitted may not finish, but that's not what happens; see this example code, which calls shutdown before it's done starting all submitted tasks:

package example;

import java.util.concurrent.*;

public class ExecutorTest {

    public static void main(String ... args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int count = i;
            executorService.execute(() -> {
                System.out.println("starting " + count);
                try {
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    System.out.println("interrupted " + count);
                }
                System.out.println("ended " + count);
            });
        }
        executorService.shutdown();         
    }    
}

Which prints:

C:\>java -cp . example.ExecutorTest
starting 0
starting 2
starting 1
ended 2
ended 0
starting 3
starting 4
ended 1
starting 5
ended 3
ended 5
ended 4
starting 7
starting 6
starting 8
ended 7
ended 6
ended 8
starting 9
ended 9

C:\>

In this example it seems pretty clear that submitted tasks do complete execution. I've run this on JDK8 with Oracle and IBM JDKs and get the same result.

So what is that line in the documentation trying to say? Or did somebody write this for shutdownNow and cut-n-paste it into the documentation for shutdown inadvertently?

xingbin :

In the doc of ThreadPoolExector#shutdown, there is one more sentence:

This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

In this context, it means the caller thread does not wait for previously submitted tasks to complete execution. In other words, shutdown() does not block the caller thread.


And if you do need block the caller thread, use ThreadPoolExector#awaitTermination(long timeout, TimeUnit unit):

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79139&siteId=1