zoukankan      html  css  js  c++  java
  • Executor

    1 Executor

    Executor是一个用于执行提交Runnable任务的接口,其核心思想在于任务的提交和运行解耦。因此在线程的使用上通常推荐使用Executor而不是显示的创建线程(利用new Thread().start()方式),其继承体系结构如下:
    image

    Executor接口内容如下

    public interface Executor {
        void execute(Runnable command);
    }
    

    注意:Executor接口并不要求task的运行时异步的,因此也能以同步方式实现。如:

    //// 同步方式实现
    class DirectExecutor implements Executor {
        public void execute(Runnable r) {
            r.run();
        }
    }
    //// 更加典型的情况是,task的执行在调用线程之外的其他线程中执行
    class ThreadPerTaskExecutor implements Executor {
        public void execute(Runnable r) {
            new Thread(r).start();
        }
    }
    

    2 ExecutorService接口

    该接口是Executor接口的扩展,在Executor接口上提供了如下功能:

    • 管理类方法:终止、等待等方法
    • 追踪异步任务进度的方法
    public interface ExecutorService extends Executor {
        /* 管理类方法 
        shutdown():允许先前提交的任务在终止之前被执行完毕,但不会接受新的任务 
        shutdownNow():尽可能停止所有正在执行的任务,停止正在等待中的任务,并且返回等待执行的任务列表。并不保证一定终止执行任务。如shutdownNow()以中断的方式实现,则不能响应中断的任务,不会被终止*/
        void shutdown();
        List<Runnable> shutdownNow();
        boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
    
        
        /* isShutdown():返回true, 表示Executor已经shutdown
        isTerminated(): 返回true:表示Executor在shutdown后,所有的线程执行完成
        awaitTermination():阻塞,直到所有的任务执行完成,或超时,或当前线程被中断;以先发生者为准 */
        boolean isShutdown();
        boolean isTerminated();
        
        <T> Future<T> submit(Callable<T> task);
        <T> Future<T> submit(Runnable task, T result);
        Future<?> submit(Runnable task);
    
        /* 关于执行方法
        invokeAll: 执行给定任务,在完成所有任务后返回持有状态和结果的List<Future>
        invokeAny: 执行给定的任务集,返回成功的结果之一(即:没有抛出异常)。若正常或异常返回,其余未完成的任务将被取消 */
        <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;
        <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;
        <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;
        <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
    }
    

    3 AbstractExecutorService

    该类是所有池化线程的抽象父类,因此该类相当有分量。根据类图可以知道,该类针对接口实现了newTaskForsubmitinvokeAllinvokeAny系列接口。

    3.1 newTaskFor()

    将给定任务打包成RunnableFuture。使用RunnableFuture接口可以获取异步结果,如:submit()方法

    // 注意,方法protected类型
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }
    

    3.2 submit()

    submit用于提交任务。提交完成之后,封装task成为RunnableFuture,然后调用execute()执行任务。具体执行方式(异步or同步)交由具体子类实现。

    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
    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;
    }
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }
    

    3.3 invoke()

    invoke即执行任务,执行任务分为两种形式:执行任务队列中的任一任务;执行所有任务。即分为invokeAnyinvokeAll,而这两种方式的执行差异极大。

    3.3.1 invokeAny()

    invokeAny()方法将操作委托给了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;
        }
    }
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return doInvokeAny(tasks, true, unit.toNanos(timeout));
    }
    

    invokeAny()方法本身将具体操作委托给了doInvokeAny()。该方法具体做了这几件事:

    • 使用ExecutorCompletionService(可参考ExecutorCompletionService类)封装该executor
    • 首先先让ExecutorCompletionService#submit()提交一个任务
    • 如果执行到for()循环中的时候,调用ExecutorCompletionService#poll()方法,获取到Future

      a. 若Future != null,说明刚才submit()的任务执行完毕,此时可以直接获取结果返回
      b. 若Future == null,说明刚才submit()的任务未执行完毕,接着利用ExecutorCompletionService#submit()中提交任务

    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(); 
        }
        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
        ExecutorCompletionService<T> ecs = new ExecutorCompletionService<T>(this);
    
        try {
            // 先使用ecs.submit()提交一个任务
            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 (;;) {
                Future<T> f = ecs.poll();
                // 若任务没有执行完毕,使用ecs.submit()继续提交任务
                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 {  
                        // 走到此处,说明任务已经全部提交,但没有一个执行完成。
                        // 所以,使用take()阻塞式的获取已经完成的任务。
                        f = ecs.take();
                    }
                }
                // 若任务已经执行完毕,可以直接返回执行结果
                if (f != null) {
                    --active;
                    try {
                        return f.get();
                    } catch (ExecutionException eex) {
                        ee = eex;
                    } catch (RuntimeException rex) {
                        ee = new ExecutionException(rex);
                    }
                }
            }
            // 如果在for循环中没有返回,则说明执行出错。
            if (ee == null) { ee = new ExecutionException(); }
            throw ee;
        } finally {
            for (int i = 0, size = futures.size(); i < size; i++)
                futures.get(i).cancel(true);
        }
    }
    

    3.3.2 invokeAll

    • 将所有任务封装为RunnableFuture,放入到集合中:futureList
    • 将所有的RunnableFuture全部使用execute()来同步或异步执行
    • 循环遍历futureList,使用RunnableFuture#isDone()来阻塞等待所有的任务执行完毕
    • 所有的任务执行完毕后,将futureList返回。
    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 {
            // execute()方法可能是异步实现,所以该循环速度极快
            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);
                // 如果该FutureTask没有执行完毕,则调用future.get()方法等待直至任务完成;若任务FutureTask执行完毕,循环下一个
                if (!f.isDone()) {
                    try {
                        f.get();
                    } 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);
        }
    }
    

    有超时机制的invokeAll()方法。需要注意,如果执行超时,所有任务全部取消(finally中的代码)。但是FutureTask代码中,是不会对执行完毕的FutureTask进行取消。因此那些完成的FutureTask任务依旧是完成的。

    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));
                    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);
            }
        }
    
  • 相关阅读:
    Ubuntu 18.04.2 LTS美化方案
    Ubuntu 16.04升级18.04
    Spark性能优化指南——高级篇
    Spark性能优化指南——基础篇
    遗传算法(Genetic Algorithm)——基于Java实现
    Linux sar命令参数详解
    Gdb调试多进程程序
    P8.打印整数
    Algorithm Book Index
    Debugging with GDB (8) 4.10 Debugging Programs with Multiple Threads
  • 原文地址:https://www.cnblogs.com/wolfdriver/p/10487426.html
Copyright © 2011-2022 走看看