java多线程 AbstractExecutorService源码分析

package java.util.concurrent;

import java.util.*;

/**
 * 提供ExecutorService方法的默认实现。
 * 这个类使用newTaskFor返回的RunnableFuture实现了submit、invokeAny和invokeAll方法,该方法默认为这个包中提供的FutureTask类。
 * 例如,submit(Runnable)的实现创建了一个关联的RunnableFuture,该RunnableFuture被执行并返回。
 * 子类可以覆盖newTaskFor方法以返回除FutureTask之外的RunnableFuture实现。
 *
 * <p>
 * 扩展的例子。下面是一个类的草图,它定制ThreadPoolExecutor来使用一个CustomTask类,而不是默认的FutureTask:
 * 
 * <pre>
 *  {@code
 * public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
 *
 *   static class CustomTask<V> implements RunnableFuture<V> {...}
 *
 *   protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
 *       return new CustomTask<V>(c);
 *   }
 *   protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
 *       return new CustomTask<V>(r, v);
 *   }
 *   // ... add constructors, etc.
 * }}
 * </pre>
 *
 * @since 1.5
 * @author Doug Lea
 */
public abstract class AbstractExecutorService implements ExecutorService {

	/**
	 * 返回给定的runnable和默认值的RunnableFuture。
	 *
	 * @param runnable the runnable task being wrapped
	 * @param value    the default value for the returned future
	 * @param <T>      the type of the given value
	 * @return a {@code RunnableFuture} which, when run, will run the underlying
	 *         runnable and which, as a {@code Future}, will yield the given value
	 *         as its result and provide for cancellation of the underlying task
	 * @since 1.6
	 */
	protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
		return new FutureTask<T>(runnable, value);
	}

	/**
	 * 返回给定可调用任务的RunnableFuture。
	 *
	 * @param callable the callable task being wrapped
	 * @param <T>      the type of the callable's result
	 * @return a {@code RunnableFuture} which, when run, will call the underlying
	 *         callable and which, as a {@code Future}, will yield the callable's
	 *         result as its result and provide for cancellation of the underlying
	 *         task
	 * @since 1.6
	 */
	protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
		return new FutureTask<T>(callable);
	}

	/**
	 * @throws RejectedExecutionException {@inheritDoc}
	 * @throws NullPointerException       {@inheritDoc}
	 */
	public Future<?> submit(Runnable task) {
		if (task == null)
			throw new NullPointerException();
		RunnableFuture<Void> ftask = newTaskFor(task, null);
		execute(ftask);
		return ftask;
	}

	/**
	 * @throws RejectedExecutionException {@inheritDoc}
	 * @throws NullPointerException       {@inheritDoc}
	 */
	public <T> Future<T> submit(Runnable task, T result) {
		if (task == null)
			throw new NullPointerException();
		RunnableFuture<T> ftask = newTaskFor(task, result);
		execute(ftask);
		return ftask;
	}

	/**
	 * @throws RejectedExecutionException {@inheritDoc}
	 * @throws NullPointerException       {@inheritDoc}
	 */
	public <T> Future<T> submit(Callable<T> task) {
		if (task == null)
			throw new NullPointerException();
		RunnableFuture<T> ftask = newTaskFor(task);
		execute(ftask);
		return ftask;
	}

	private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks, boolean timed, long nanos)
			throws InterruptedException, ExecutionException, TimeoutException {
		if (tasks == null)
			throw new NullPointerException();
		int ntasks = tasks.size();
		if (ntasks == 0)
			throw new IllegalArgumentException();
		// 含有结果的Future队列
		ArrayList<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
		// 将本对象作为Executor创建ExecutorCompletionService对象
		ExecutorCompletionService<T> ecs = new ExecutorCompletionService<T>(this);

		try {
			// 记录可能抛出的执行异常
			ExecutionException ee = null;
			// 初始化超时时间
			final long deadline = timed ? System.nanoTime() + nanos : 0L;
			Iterator<? extends Callable<T>> it = tasks.iterator();

			// 确定在主循环之前开始一个任务
			futures.add(ecs.submit(it.next()));
			--ntasks;
			int active = 1; // 记录正在执行的任务数量

			for (;;) {
				// 获取并移除下一个将要完成的任务的结果表示,如果没有任何表示则返回null
				Future<T> f = ecs.poll();// 底层调用队列的poll方法(非阻塞)
				if (f == null) { // 没有结果表示
					if (ntasks > 0) { // 如果还有剩余的任务,则提交下一个任务
						--ntasks;
						futures.add(ecs.submit(it.next()));
						++active;
					}
					// 出现这种情况说明,已经有任务完成,并返回结果表示,但是
					// 捕获到了异常,则跳出主循环,进行异常的抛出
					else if (active == 0)
						break;
					else if (timed) { // 超时获取结果表示
						f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
						if (f == null)
							throw new TimeoutException();
						nanos = deadline - System.nanoTime();
					} else // 阻塞获取结果表示
						f = ecs.take();
				}
				if (f != null) { // 含有结果表示
					--active;
					try {
						return f.get(); // 返回结果
					} catch (ExecutionException eex) {
						ee = eex;
					} catch (RuntimeException rex) {
						ee = new ExecutionException(rex);
					}
				}
			}

			if (ee == null)
				ee = new ExecutionException();
			throw ee;

		} finally { // 最后取消所有提交的任务
			for (int i = 0, size = futures.size(); i < size; i++)
				futures.get(i).cancel(true);
		}
	}

	// 对doInvokeAny的封装,实现无超时等待的版本
	public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
		try {
			return doInvokeAny(tasks, false, 0);
		} catch (TimeoutException cannotHappen) {
			assert false;
			return null;
		}
	}

	// 对doInvokeAny的封装,实现超时等待的版本
	public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
			throws InterruptedException, ExecutionException, TimeoutException {
		return doInvokeAny(tasks, true, unit.toNanos(timeout));
	}

    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
            throws InterruptedException {
            if (tasks == null)
                throw new NullPointerException();
            ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
            boolean done = false; // 所有任务是否完成的标志
            try {
                // 对所有任务进行包装,并提交任务,并将返回的结果添加到futures集合中
                for (Callable<T> t : tasks) { 
                    RunnableFuture<T> f = newTaskFor(t);
                    futures.add(f);
                    execute(f);
                }
                // 对所有结果进行判断或者阻塞等待结果返回
                for (int i = 0, size = futures.size(); i < size; i++) {
                    Future<T> f = futures.get(i);
                    if (!f.isDone()) { // 如果任务没有完成
                        try {
                            f.get(); // 则阻塞等待结果返回,并压制异常
                        } catch (CancellationException ignore) {
                        } catch (ExecutionException ignore) {
                        }
                    }
                }
                // 当所有任务已经完成了(不管是正常完成还是异常完成,
                // 如发生CancellationException、ExecutionException ),
                // 则将完成标志设为true,并返回结果集合
                done = true; 
                return futures;
            } finally {
                if (!done) // 如果发生中断异常InterruptedException 则取消已经提交的任务
                    for (int i = 0, size = futures.size(); i < size; i++)
                        futures.get(i).cancel(true);
            }
        }

        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                             long timeout, TimeUnit unit)
            throws InterruptedException {
            if (tasks == null)
                throw new NullPointerException();
            long nanos = unit.toNanos(timeout);
            ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
            boolean done = false; 
            try {
                for (Callable<T> t : tasks)
                    futures.add(newTaskFor(t));

                final long deadline = System.nanoTime() + nanos;
                final int size = futures.size();

                for (int i = 0; i < size; i++) {
                    execute((Runnable)futures.get(i));
                    // 在添加执行任务时超时判断,如果超时则立刻返回futures集合
                    nanos = deadline - System.nanoTime();
                    if (nanos <= 0L)
                        return futures;
                }
                // 每次对结果进行判断时都进行超时判断
                for (int i = 0; i < size; i++) {
                    Future<T> f = futures.get(i);
                    if (!f.isDone()) { // 判断超时
                        if (nanos <= 0L)
                            return futures;
                        try {
                            f.get(nanos, TimeUnit.NANOSECONDS);
                        } catch (CancellationException ignore) {
                        } catch (ExecutionException ignore) {
                        } catch (TimeoutException toe) {
                            return futures;
                        }
                        nanos = deadline - System.nanoTime(); // 更新剩余时间
                    }
                }
                done = true;
                return futures;
            } finally {
                if (!done)
                    for (int i = 0, size = futures.size(); i < size; i++)
                        futures.get(i).cancel(true);
            }
        }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值