is invokeAll() a blocking call in java 7

后端 未结 2 1823
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 10:15
ExecutorService executorService = Executors.newSingleThreadExecutor();

Set> callables = new HashSet>();

c         


        
2条回答
  •  臣服心动
    2021-01-18 11:04

    Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

    Futures can only be done when execution is finished, therefore this method can only return when the tasks have been executed.

    That it can throw an InterruptedException is also indicative of a blocking action.

    Looking at the implementation of invokeAll in java.util.concurrent.AbstractExecutorService (comment inline):

    // from OpenJDK source; GPL-2.0-with-classpath-exception
    public  List> invokeAll(Collection> tasks)
        throws InterruptedException {
        if (tasks == null)
            throw new NullPointerException();
        ArrayList> futures = new ArrayList>(tasks.size());
        boolean done = false;
        try {
            for (Callable t : tasks) {
                RunnableFuture f = newTaskFor(t);
                futures.add(f);
                execute(f);
            }
            for (int i = 0, size = futures.size(); i < size; i++) {
                Future f = futures.get(i);
                if (!f.isDone()) {
                    try {
                        f.get(); // <== *** BLOCKS HERE ***
    
                    } catch (CancellationException ignore) {
                    } catch (ExecutionException ignore) {
                    }
                }
            }
            done = true;
            return futures;
        } finally {
            if (!done)
                for (int i = 0, size = futures.size(); i < size; i++)
                    futures.get(i).cancel(true);
        }
    }
    

    In fact, looking at a reference implementation is what you generally should do in these cases when the Javadoc-Specese appears to be difficult to decipher. (with the caveat in mind that some implementation details are not part of the spec.)

提交回复
热议问题