• CompletionService 和 CompletableFuture


    【参考】:https://blog.csdn.net/sermonlizhi/article/details/123314335
    【参考】:https://blog.csdn.net/sermonlizhi/article/details/123356877

    对于Future存在的局限性,CompletionService和CompletableFuture可以解决。

    CompletionService

    CompletionService的主要功能是一边生成任务,一边获取任务的返回值。让两件事分开执行,任务之间不会互相阻塞,可以实现先执行完的先取结果,不再依赖任务顺序了。

    内部通过阻塞队列+FutureTask,实现了任务先完成可优先获取到,即结果按照完成先后顺序排序,内部有一个先进先出的阻塞队列,用于保存已经执行完成的Future,通过调用它的take()或poll()可以获取到一个已经执行完成的Future,进而通过调用Future接口实现类的get方法获取最终的结果

    package java.util.concurrent;
    
    public class ExecutorCompletionService<V> implements CompletionService<V> {
        //执行任务的线程
        private final Executor executor;
        private final AbstractExecutorService aes;
        //任务完成会记录在该队列中
        private final BlockingQueue<Future<V>> completionQueue;
        //内部类:实现了FutureTask接口,当任务执行时,会去调用FutureTask的run()
        private class QueueingFuture extends FutureTask<Void> {
            QueueingFuture(RunnableFuture<V> task) {
                super(task, null);
                this.task = task;
            }
            protected void done() { completionQueue.add(task); }
            private final Future<V> task;
        }
        //两个封装RunnableFuture 参数 最终调用的都是FutureTask的构造方法
        // 封装RunnableFuture 参数:Callable task
        private RunnableFuture<V> newTaskFor(Callable<V> task) {
            if (aes == null)
                return new FutureTask<V>(task);
            else
                return aes.newTaskFor(task);
        }
        //封装RunnableFuture 参数:Runnable task, V result
        private RunnableFuture<V> newTaskFor(Runnable task, V result) {
            if (aes == null)
                return new FutureTask<V>(task, result);
            else
                return aes.newTaskFor(task, result);
        }
        //构造方法 参数:Executor executor
        public ExecutorCompletionService(Executor executor) {
            if (executor == null)
                throw new NullPointerException();
            this.executor = executor;
            this.aes = (executor instanceof AbstractExecutorService) ?
                (AbstractExecutorService) executor : null;
            this.completionQueue = new LinkedBlockingQueue<Future<V>>();
        }
        //构造方法 参数Executor executor, BlockingQueue> completionQueue
        public ExecutorCompletionService(Executor executor,
                                         BlockingQueue<Future<V>> completionQueue) {
            if (executor == null || completionQueue == null)
                throw new NullPointerException();
            this.executor = executor;
            this.aes = (executor instanceof AbstractExecutorService) ?
                (AbstractExecutorService) executor : null;
            this.completionQueue = completionQueue;
        }
        //两个任务提交方法:内部都会将其转换为RunnableFutuer实例,然后再封装成QueueingFuture实例作为任务来执行
        // 任务提交方法:Callable task
        public Future<V> submit(Callable<V> task) {
            if (task == null) throw new NullPointerException();
            RunnableFuture<V> f = newTaskFor(task);
            executor.execute(new QueueingFuture(f));
            return f;
        }
        // 任务提交方法: 参数 Runnable task, V result
        public Future<V> submit(Runnable task, V result) {
            if (task == null) throw new NullPointerException();
            RunnableFuture<V> f = newTaskFor(task, result);
            executor.execute(new QueueingFuture(f));
            return f;
        }
    
        public Future<V> take() throws InterruptedException {
            return completionQueue.take();
        }
    
        public Future<V> poll() {
            return completionQueue.poll();
        }
    
        public Future<V> poll(long timeout, TimeUnit unit)
                throws InterruptedException {
            return completionQueue.poll(timeout, unit);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 两个封装RunnableFuture 方法 最终调用的都是FutureTask的构造方法
      private RunnableFuture newTaskFor(…)
    • 两个构造方法 参数Executor executor 和 Executor executor, BlockingQueue completionQueue
    • 两个任务提交方法:内部都会将其转换为RunnableFutuer实例,然后再封装成QueueingFuture实例作为任务来执行
    • 一个内部类:实现了FutureTask接口,当任务执行时,会去调用FutureTask的run(), 在任务执行成功,记录返回记录结果的时候,会调用finishCompletion()去唤醒所有阻塞的线程并调用done()方法。而QueueingFuture内部类就实现了done()方法,它将执行完的FutureTask放入到阻塞队列中,当调用take()方法时就可以取到任务的执行结果,如果任务都还没有执行完,就阻塞。
    package java.util.concurrent;
    
    public interface CompletionService<V> {
        Future<V> submit(Callable<V> task);
        Future<V> submit(Runnable task, V result);
        Future<V> take() throws InterruptedException;
        Future<V> poll();
        Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    应用场景

    • 当需要批量提交异步任务的时候建议使用CompletionService。CompletionService将线程池Executor和阻塞队列BlockingQueue的功能融合在了一起,能够让批量异步任务的管理更简单。
    • CompletionService能够让异步任务的执行结果有序化。先执行完的先进入阻塞队列,利用这个特性,你可以轻松实现后续处理的有序性,避免无谓的等待,同时还可以快速实现诸如Forking Cluster这样的需求。
    • 线程池隔离。CompletionService支持自己创建线程池,这种隔离性能避免几个特别耗时的任务拖垮整个应用的风险。

    Future方式

    向不同电商平台询价,并保存价格,采用ThreadPoolExecutor+Future的方案:异步执行询价然后再保存

            //    创建线程池
            ExecutorService executor = Executors.newFixedThreadPool(2);
           //    异步向电商S1询价 
            Future<Integer> f1 = executor.submit(()->getPriceByS1());
           //    异步向电商S2询价 
            Future<Integer> f2= executor.submit(()->getPriceByS2());
          //    获取电商S1报价并异步保存 
            executor.execute(()->save(f1.get()));
          //    获取电商S2报价并异步保存 
            executor.execute(()->save(f2.get())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    问题:如果获取电商S1报价的耗时很长,那么即便获取电商S2报价的耗时很短,也无法让保存S2报价的操作先执行,因为这个主线程都阻塞 在了f1.get()操作上。

    CompletionService方式

    //创建线程池
    ExecutorService executor = Executors.newFixedThreadPool(10);
    //创建CompletionService
    CompletionService<Integer> cs = new ExecutorCompletionService<>(executor);
    //异步向电商S1询价
    cs.submit(() -> getPriceByS1());
    //异步向电商S2询价
    cs.submit(() -> getPriceByS2());
    //将询价结果异步保存到数据库
    for (int i = 0; i < 2; i++) {
        Integer r = cs.take().get();
        executor.execute(() -> save(r));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    CompletableFuture

    CompletableFuture实现了Future接口,是对Future的扩展和增强。 同时CompletableFuture实现了对任务编排的能力,可以组织不同任务的运行顺序、规则以及方式。

    public class CompletableFuture<T> implements Future<T>, CompletionStage<T> 
    
    • 1

    CompletionStage

    接口定义了任务编排的方法,执行某一阶段,可以向下执行后续阶段。
    异步执行的,默认线程池是ForkJoinPool.commonPool(),但为了业务之间互不影响,且便于定位问题,推荐使用自定义线程池。

    CompletableFuture中默认线程池如下:

    // 根据commonPool的并行度来选择,而并行度的计算是在ForkJoinPool的静态代码段完成的
    private static final boolean useCommonPool = (ForkJoinPool.getCommonPoolParallelism() > 1);
    
    private static final Executor asyncPool = useCommonPool ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
    
    • 1
    • 2
    • 3
    • 4

    ForkJoinPool中初始化commonPool的参数

    static {
        // initialize field offsets for CAS etc
        try {
            U = sun.misc.Unsafe.getUnsafe();
            Class<?> k = ForkJoinPool.class;
            CTL = U.objectFieldOffset
                (k.getDeclaredField("ctl"));
            RUNSTATE = U.objectFieldOffset
                (k.getDeclaredField("runState"));
            STEALCOUNTER = U.objectFieldOffset
                (k.getDeclaredField("stealCounter"));
            Class<?> tk = Thread.class;
            ……
        } catch (Exception e) {
            throw new Error(e);
        }
    
        commonMaxSpares = DEFAULT_COMMON_MAX_SPARES;
        defaultForkJoinWorkerThreadFactory =
            new DefaultForkJoinWorkerThreadFactory();
        modifyThreadPermission = new RuntimePermission("modifyThread");
    
        // 调用makeCommonPool方法创建commonPool,其中并行度为逻辑核数-1
        common = java.security.AccessController.doPrivileged
            (new java.security.PrivilegedAction<ForkJoinPool>() {
                public ForkJoinPool run() { return makeCommonPool(); }});
        int par = common.config & SMASK; // report 1 even if threads disabled
        commonParallelism = par > 0 ? par : 1;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    功能

    常用方法

    依赖关系

    • thenApply():接收一个函数作为参数,使用该函数处理上一个CompletableFuture调用的结果,并返回一个具有处理结果的Future对象。
    public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
    
    • 1
    • 2
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                int result = 100;
                System.out.println("第一次运算:" + result);
                return result;
            }).thenApply(number -> {
                int result = number * 3;
                System.out.println("第二次运算:" + result);
                return result;
            });
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在这里插入图片描述

    • thenCompose():thenCompose的参数为一个返回CompletableFuture实例的函数,该函数的参数是先前计算步骤的结果。
    public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
    public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) ;
    
    • 1
    • 2
    public static void main(String[] args) throws ExecutionException, InterruptedException {
            CompletableFuture<Integer> future = CompletableFuture
                    .supplyAsync(new Supplier<Integer>() {
                        @Override
                        public Integer get() {
                            int number = new Random().nextInt(30);
                            System.out.println("第一次运算:" + number);
                            return number;
                        }
                    })
                    .thenCompose(new Function<Integer, CompletionStage<Integer>>() {
                        @Override
                        public CompletionStage<Integer> apply(Integer param) {
                            return CompletableFuture.supplyAsync(new Supplier<Integer>() {
                                @Override
                                public Integer get() {
                                    int number = param * 2;
                                    System.out.println("第二次运算:" + number);
                                    return number;
                                }
                            });
                        }
                    });
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述
    区别

    • thenApply转换的是泛型中的类型,返回的是同一个CompletableFuture;
    • thenCompose将内部的CompletableFuture调用展开来并使用上一个CompletableFutre调用的结果在下一步的CompletableFuture调用中进行运算,是生成一个新的CompletableFuture。

    结果消费

    • thenAccept():对单个结果进行消费
    public CompletionStage<Void> thenAccept(Consumer<? super T> action);
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
    
    • 1
    • 2
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            CompletableFuture<Void> future = CompletableFuture
                    .supplyAsync(() -> {
                        int number = new Random().nextInt(10);
                        System.out.println("第一次运算:" + number);
                        return number;
                    }).thenAccept(number ->
                            System.out.println("第二次运算:" + number * 5));
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    • thenAcceptBoth():对两个结果进行消费
      作用是,当两个CompletionStage都正常完成计算的时候,就会执行提供的action消费两个异步的结果。
    public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
    public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
    
    
    • 1
    • 2
    • 3
    public static void main(String[] args) throws ExecutionException, InterruptedException {
            CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    int number = new Random().nextInt(3) + 1;
                    try {
                        TimeUnit.SECONDS.sleep(number);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("任务1结果:" + number);
                    return number;
                }
            });
    
            CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    int number = new Random().nextInt(3) + 1;
                    try {
                        TimeUnit.SECONDS.sleep(number);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("任务2结果:" + number);
                    return number;
                }
            });
    
            future1.thenAcceptBoth(future2, new BiConsumer<Integer, Integer>() {
                @Override
                public void accept(Integer x, Integer y) {
                    System.out.println("最终结果:" + (x + y));
                }
            });
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • thenRun():不关心结果,只对结果执行Action
      thenRun是对线程任务结果的一种消费函数,与thenAccept不同的是,thenRun会在上一阶段 CompletableFuture计算完成的时候执行一个Runnable,而Runnable并不使用该CompletableFuture计算的结果。
    public CompletionStage<Void> thenRun(Runnable action);
    public CompletionStage<Void> thenRunAsync(Runnable action);
    
    
    • 1
    • 2
    • 3
    public static void main(String[] args) throws ExecutionException, InterruptedException {
            
            CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
                int number = new Random().nextInt(10);
                System.out.println("第一阶段:" + number);
                return number;
            }).thenRun(() ->
                    System.out.println("thenRun 执行"));
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    and集合关系

    • thenCombine():合并任务,有返回值
    public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
    
    public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
    
    public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            CompletableFuture<Integer> future1 = CompletableFuture
                    .supplyAsync(new Supplier<Integer>() {
                        @Override
                        public Integer get() {
                            int number = new Random().nextInt(10);
                            System.out.println("任务1结果:" + number);
                            return number;
                        }
                    });
            CompletableFuture<Integer> future2 = CompletableFuture
                    .supplyAsync(new Supplier<Integer>() {
                        @Override
                        public Integer get() {
                            int number = new Random().nextInt(10);
                            System.out.println("任务2结果:" + number);
                            return number;
                        }
                    });
            CompletableFuture<Integer> result = future1
                    .thenCombine(future2, new BiFunction<Integer, Integer, Integer>() {
                        @Override
                        public Integer apply(Integer x, Integer y) {
                            return x + y;
                        }
                    });
            System.out.println("组合后结果:" + result.get());
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在这里插入图片描述

    • thenAccepetBoth():两个任务执行完成后,将结果交给thenAccepetBoth处理,无返回值
    • runAfterBoth():两个任务都执行完成后,执行下一步操作(Runnable类型任务)

    or聚合关系

    • applyToEither():两个任务哪个执行的快,就使用哪一个结果,有返回值
    public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
    public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
    
    
    • 1
    • 2
    • 3
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            CompletableFuture<Integer> future1 = CompletableFuture
                    .supplyAsync(new Supplier<Integer>() {
                        @Override
                        public Integer get() {
                            int number = new Random().nextInt(10);
                            try {
                                TimeUnit.SECONDS.sleep(number);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println("任务1结果:" + number);
                            return number;
                        }
                    });
            CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    int number = new Random().nextInt(10);
                    try {
                        TimeUnit.SECONDS.sleep(number);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("任务2结果:" + number);
                    return number;
                }
            });
    
            future1.applyToEither(future2, new Function<Integer, Integer>() {
                @Override
                public Integer apply(Integer number) {
                    System.out.println("最快结果:" + number);
                    return number * 2;
                }
            });
    
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • acceptEither():两个任务哪个执行的快,就消费哪一个结果,无返回值
    public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
    public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
    
    
    • 1
    • 2
    • 3
     public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    int number = new Random().nextInt(10) + 1;
                    try {
                        TimeUnit.SECONDS.sleep(number);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("第一阶段:" + number);
                    return number;
                }
            });
    
            CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    int number = new Random().nextInt(10) + 1;
                    try {
                        TimeUnit.SECONDS.sleep(number);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("第二阶段:" + number);
                    return number;
                }
            });
    
            future1.acceptEither(future2, new Consumer<Integer>() {
                @Override
                public void accept(Integer number) {
                    System.out.println("最快结果:" + number);
                }
            });
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • runAfterEither():任意一个任务执行完成,进行下一步操作(Runnable类型任务)
    public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
    public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
    
    
    • 1
    • 2
    • 3
    CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(5);
            try {
                TimeUnit.SECONDS.sleep(number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务1结果:" + number);
            return number;
        }
    });
    
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            int number = new Random().nextInt(5);
            try {
                TimeUnit.SECONDS.sleep(number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务2结果:" + number);
            return number;
        }
    });
    
    future1.runAfterEither(future2, new Runnable() {
        @Override
        public void run() {
            System.out.println("已经有一个任务完成了");
        }
    }).join();
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    并行执行

    • allOf():当所有给定的 CompletableFuture 完成时,返回一个新的 CompletableFuture
    public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
    
    • 1
    CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("future1完成!");
        return "future1完成!";
    });
    
    CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
        System.out.println("future2完成!");
        return "future2完成!";
    });
    
    CompletableFuture<Void> combindFuture = CompletableFuture.allOf(future1, future2);
    
    try {
        combindFuture.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • anyOf():当任何一个给定的CompletablFuture完成时,返回一个新的CompletableFuture
    public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
    
    • 1
    Random random = new Random();
    CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
        try {
            TimeUnit.SECONDS.sleep(random.nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    });
    
    CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
        try {
            TimeUnit.SECONDS.sleep(random.nextInt(1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "world";
    });
    CompletableFuture<Object> result = CompletableFuture.anyOf(future1, future2);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    结果处理

    • whenComplete:当任务完成时,将使用结果(或 null)和此阶段的异常(或 null如果没有)执行给定操作
    • exceptionally:返回一个新的CompletableFuture,当前面的CompletableFuture完成时,它也完成,当它异常完成时,给定函数的异常触发这个CompletableFuture的完成
    异步操作

    CompletableFuture提供了四个静态方法来创建一个异步操作:

    public static CompletableFuture<Void> runAsync(Runnable runnable)
    public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
    
    • 1
    • 2
    • 3
    • 4

    区别:

    • runAsync() 以Runnable函数式接口类型为参数,没有返回结果,supplyAsync() 以Supplier函数式接口类型为参数,返回结果类型为U;Supplier接口的 get()是有返回值的(会阻塞)
    • 使用没有指定Executor的方法时,内部使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。
    • 默认情况下CompletableFuture会使用公共的ForkJoinPool线程池,这个线程池默认创建的线程数是 CPU 的核数(也可以通过 JVM option:-Djava.util.concurrent.ForkJoinPool.common.parallelism 来设置ForkJoinPool线程池的线程数)。如果所有CompletableFuture共享一个线程池,那么一旦有任务执行一些很慢的 I/O 操作,就会导致线程池中所有线程都阻塞在 I/O 操作上,从而造成线程饥饿,进而影响整个系统的性能。所以,强烈建议你要根据不同的业务类型创建不同的线程池,以避免互相干扰
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            Runnable runnable = () -> System.out.println("无返回结果异步任务");
            CompletableFuture.runAsync(runnable);
    
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                System.out.println("有返回值的异步任务");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "Hello World";
            });
            String result = future.get();
    
            System.out.println(result);
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    获取结果(join&get)

    join()和get()方法都是用来获取CompletableFuture异步之后的返回值。

    • join()方法抛出的是uncheck异常(即未经检查的异常),不会强制开发者抛出。
    • get()方法抛出的是经过检查的异常,ExecutionException, InterruptedException 需要用户手动处理(抛出或者 try catch)
    结果处理

    当CompletableFuture的计算结果完成,或者抛出异常的时候,我们可以执行特定的 Action。主要是下面的方法:

    public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
    
    • 1
    • 2
    • 3
    • Action的类型是BiConsumer,它可以处理正常的计算结果,或者异常情况。
    • 方法不以Async结尾,意味着Action使用相同的线程执行,而Async可能会使用其它的线程去执行(如果使用相同的线程池,也可能会被同一个线程选中执行)。
    • 这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                }
                if (new Random().nextInt(10) % 2 == 0) {
                    int i = 12 / 0;
                }
                System.out.println("执行结束!");
                return "test";
            });
            // 任务完成或异常方法完成时执行该方法
            // 如果出现了异常,任务结果为null
            future.whenComplete(new BiConsumer<String, Throwable>() {
                @Override
                public void accept(String t, Throwable action) {
                    System.out.println(t+" 执行完成!");
                }
            });
            // 出现异常时先执行该方法
            future.exceptionally(new Function<Throwable, String>() {
                @Override
                public String apply(Throwable t) {
                    System.out.println("执行失败:" + t.getMessage());
                    return "异常xxxx";
                }
            });
    
            future.get();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    在这里插入图片描述

    使用案例

    实现最优的“烧水泡茶”程序
    在这里插入图片描述

    对于烧水泡茶这个程序,一种最优的分工方案:用两个线程 T1 和 T2 来完成烧水泡茶程序,T1 负责洗水壶、烧开水、泡茶这三道工序,T2 负责洗茶壶、洗茶杯、拿茶叶三道工序,其中 T1 在执行泡茶这道工序时需要等待 T2 完成拿茶叶的工序。

    基于Future实现

    public class FutureTaskTest{
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            // 创建任务T2的FutureTask
            FutureTask<String> ft2 = new FutureTask<>(new T2Task());
            // 创建任务T1的FutureTask
            FutureTask<String> ft1 = new FutureTask<>(new T1Task(ft2));
    
            // 线程T1执行任务ft2
            Thread T1 = new Thread(ft2);
            T1.start();
            // 线程T2执行任务ft1
            Thread T2 = new Thread(ft1);
            T2.start();
            // 等待线程T1执行结果
            System.out.println(ft1.get());
    
        }
    }
    
    // T1Task需要执行的任务:
    // 洗水壶、烧开水、泡茶
    class T1Task implements Callable<String> {
        FutureTask<String> ft2;
        // T1任务需要T2任务的FutureTask
        T1Task(FutureTask<String> ft2){
            this.ft2 = ft2;
        }
        @Override
        public String call() throws Exception {
            System.out.println("T1:洗水壶...");
            TimeUnit.SECONDS.sleep(1);
    
            System.out.println("T1:烧开水...");
            TimeUnit.SECONDS.sleep(15);
            // 获取T2线程的茶叶
            String tf = ft2.get();
            System.out.println("T1:拿到茶叶:"+tf);
    
            System.out.println("T1:泡茶...");
            return "上茶:" + tf;
        }
    }
    // T2Task需要执行的任务:
    // 洗茶壶、洗茶杯、拿茶叶
    class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T2:洗茶壶...");
            TimeUnit.SECONDS.sleep(1);
    
            System.out.println("T2:洗茶杯...");
            TimeUnit.SECONDS.sleep(2);
    
            System.out.println("T2:拿茶叶...");
            TimeUnit.SECONDS.sleep(1);
            return "龙井";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    基于CompletableFuture实现

    public class CompletableFutureTest {
    
        public static void main(String[] args) {
    
            //任务1:洗水壶->烧开水
            CompletableFuture<Void> f1 = CompletableFuture
                .runAsync(() -> {
                    System.out.println("T1:洗水壶...");
                    sleep(1, TimeUnit.SECONDS);
    
                    System.out.println("T1:烧开水...");
                    sleep(15, TimeUnit.SECONDS);
                });
            //任务2:洗茶壶->洗茶杯->拿茶叶
            CompletableFuture<String> f2 = CompletableFuture
                .supplyAsync(() -> {
                    System.out.println("T2:洗茶壶...");
                    sleep(1, TimeUnit.SECONDS);
    
                    System.out.println("T2:洗茶杯...");
                    sleep(2, TimeUnit.SECONDS);
    
                    System.out.println("T2:拿茶叶...");
                    sleep(1, TimeUnit.SECONDS);
                    return "龙井";
                });
            //任务3:任务1和任务2完成后执行:泡茶
            CompletableFuture<String> f3 = f1.thenCombine(f2, (__, tf) -> {
                System.out.println("T1:拿到茶叶:" + tf);
                System.out.println("T1:泡茶...");
                return "上茶:" + tf;
            });
            //等待任务3执行结果
            System.out.println(f3.join());
        }
    
        static void sleep(int t, TimeUnit u){
            try {
                u.sleep(t);
            } catch (InterruptedException e) {
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    利用 CompletableFuture 实现“旅游平台”问题

    旅游平台问题

    一个旅游平台用户想同时获取多家航空公司的航班信息。比如,从北京到上海的机票钱是多少?有很多家航空公司都有这样的航班信息,所以应该把所有航空公司的航班、票价等信息都获取到,然后再聚合。由于每个航空公司都有自己的服务器,所以分别去请求它们的服务器就可以了。

    串行

    效率低

    并行

    并行地去获取这些机票信息,然后再把机票信息给聚合起来。
    缺点:那就是会“一直等到所有请求都返回”。如果有一个网站特别慢,要一直等。

    有超时的并行获取

    有超时的并行获取,同样也在并行的去请求各个网站信息。但是我们规定了一个时间的超时,比如 3 秒钟,那么到 3 秒钟的时候如果都已经返回了那当然最好,把它们收集起来即可;但是如果还有些网站没能及时返回,我们就把这些请求给忽略掉,这样一来用户体验就比较好了,它最多只需要等固定的 3 秒钟就能拿到信息,虽然拿到的可能不是最全的,但是总比一直等更好。

    方案
    1.线程池实现

    public class ThreadPoolDemo {
         
         //一个固定 3 线程的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
    
        public static void main(String[] args) throws InterruptedException {
            ThreadPoolDemo threadPoolDemo = new ThreadPoolDemo();
            System.out.println(threadPoolDemo.getPrices());
        }
    
        private Set<Integer> getPrices() throws InterruptedException {
            //新建了一个线程安全的 Set,它是用来存储各个价格信息的,把它命名为 Prices,然后往线程池中去放任务。
            Set<Integer> prices = Collections.synchronizedSet(new HashSet<Integer>());
            //新建了三个任务,productId 分别是 123、456、789,这里的 productId 并不重要,因为返回的价格是随机的,
            //为了实现超时等待的功能,这里调用了 Thread 的 sleep 方法来休眠 3 秒钟,这样做的话,它就会在这里等待 3 秒,之后直接返回 prices。
            //如果前面响应速度快的话,prices 里面最多会有三个值,但是如果每一个响应时间都很慢,那么可能 prices 里面一个值都没有。不论有多少个,它都会在休眠结束之后,也就是执行完 Thread 的 sleep 之后直接把 prices 返回,并且最终在 main 函数中把这个结果给打印出来。
            threadPool.submit(new Task(123, prices));
            threadPool.submit(new Task(456, prices));
            threadPool.submit(new Task(789, prices));
            Thread.sleep(3000);
            return prices;
        }
    
        private class Task implements Runnable {
    
            Integer productId;
            Set<Integer> prices;
            public Task(Integer productId, Set<Integer> prices) {
                this.productId = productId;
                this.prices = prices;
            }
    
           //用一个随机的时间去模拟各个航空网站的响应时间,然后再去返回一个随机的价格来表示票价,最后把这个票价放到 Set 中
            @Override
            public void run() {
                int price=0;
                try {
                    Thread.sleep((long) (Math.random() * 4000));
                    price= (int) (Math.random() * 4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                prices.add(price);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    结果,一种可能性就是有 3 个值,即 [3815, 3609, 3819](数字是随机的);有可能是 1 个 [3496]、或 2 个 [1701, 2730],如果每一个响应速度都特别慢,可能一个值都没有。

    2.CountDownLatch

    优化:比如说网络特别好时,每个航空公司响应速度都特别快,不需要等三秒,有的航空公司可能几百毫秒就返回了,那么也不应该让用户等 3 秒。所以需要进行一下这样的改进

    public class CountDownLatchDemo {
    
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
    
        public static void main(String[] args) throws InterruptedException {
            CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo();
            System.out.println(countDownLatchDemo.getPrices());
        }
    
        private Set<Integer> getPrices() throws InterruptedException {
            Set<Integer> prices = Collections.synchronizedSet(new HashSet<Integer>());
            CountDownLatch countDownLatch = new CountDownLatch(3);
            threadPool.submit(new Task(123, prices, countDownLatch));
            threadPool.submit(new Task(456, prices, countDownLatch));
            threadPool.submit(new Task(789, prices, countDownLatch));
            countDownLatch.await(3, TimeUnit.SECONDS);
            return prices;
        }
    
        private class Task implements Runnable {
    
            Integer productId;
            Set<Integer> prices;
            CountDownLatch countDownLatch;
    
            public Task(Integer productId, Set<Integer> prices,
                    CountDownLatch countDownLatch) {
                this.productId = productId;
                this.prices = prices;
                this.countDownLatch = countDownLatch;
            }
    
            @Override
            public void run() {
                int price = 0;
                try {
                    Thread.sleep((long) (Math.random() * 4000));
                    price = (int) (Math.random() * 4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                prices.add(price);
                countDownLatch.countDown();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    CountDownLatch 实现了这个功能,整体思路和之前是一致的,不同点在于新增了一个 CountDownLatch,并且把它传入到了 Task 中。在 Task 中,获取完机票信息并且把它添加到 Set 之后,会调用 countDown 方法,相当于把计数减 1。

    在执行 countDownLatch.await(3, TimeUnit.SECONDS) 这个函数进行等待时,如果三个任务都非常快速地执行完毕了,那么三个线程都已经执行了 countDown 方法,那么这个 await 方法就会立刻返回,不需要等到 3 秒钟。

    如果有一个请求特别慢,相当于有一个线程没有执行 countDown 方法,来不及在 3 秒钟之内执行完毕,那么这个带超时参数的 await 方法也会在 3 秒钟到了以后,及时地放弃这一次等待,于是就把 prices 给返回了。所以利用 CountDownLatch 实现了这个需求,也就是说我们最多等 3 秒钟,但如果在 3 秒之内全都返回了,也可以快速地去返回。

    3.CompletableFuture

    public class CompletableFutureDemo {
    
        public static void main(String[] args) throws Exception {
            CompletableFutureDemo completableFutureDemo = new CompletableFutureDemo();
            System.out.println(completableFutureDemo.getPrices());
        }
    
        private Set<Integer> getPrices() {
            Set<Integer> prices = Collections.synchronizedSet(new HashSet<Integer>());
            CompletableFuture<Void> task1 = CompletableFuture.runAsync(new Task(123, prices));
            CompletableFuture<Void> task2 = CompletableFuture.runAsync(new Task(456, prices));
            CompletableFuture<Void> task3 = CompletableFuture.runAsync(new Task(789, prices));
            CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2, task3);
            try {
                allTasks.get(3, TimeUnit.SECONDS);
            } catch (InterruptedException e) 
            } catch (ExecutionException e) {
            } catch (TimeoutException e) {
            }
            return prices;
    
        }
    
        private class Task implements Runnable {
    
            Integer productId;
            Set<Integer> prices;
    
            public Task(Integer productId, Set<Integer> prices) {
                this.productId = productId;
                this.prices = prices;
            }
    
            @Override
    
            public void run() {
    
                int price = 0;
                try {
                    Thread.sleep((long) (Math.random() * 4000));
                    price = (int) (Math.random() * 4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                prices.add(price);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    用了CompletableFuture 的 runAsync 异步的去执行任务。

    有三个任务,并且在执行这个代码之后会分别返回一个 CompletableFuture 对象,命名为 task 1、task 2、task 3,然后执行 CompletableFuture 的 allOf 方法,并且把 task 1、task 2、task 3 传入。这个方法的作用是把多个 task 汇总,然后可以根据需要去获取到传入参数的这些 task 的返回结果,或者等待它们都执行完毕等。就把这个返回值叫作 allTasks,并且在下面调用它的带超时时间的 get 方法,同时传入 3 秒钟的超时参数。

    这样如果在 3 秒钟之内这 3 个任务都可以顺利返回,也就是这个任务包括的那三个任务,每一个都执行完毕的话,则这个 get 方法就可以及时正常返回,并且往下执行,相当于执行到 return prices。在下面的这个 Task 的 run 方法中,该方法如果执行完毕的话,对于 CompletableFuture 而言就意味着这个任务结束,它是以这个作为标记来判断任务是不是执行完毕的。但是如果有某一个任务没能来得及在 3 秒钟之内返回,那么这个带超时参数的 get 方法便会抛出 TimeoutException 异常,同样会被我们给 catch 住。这样一来它就实现了这样的效果:会尝试等待所有的任务完成,但是最多只会等 3 秒钟,在此之间,如及时完成则及时返回。那么所以我们利用 CompletableFuture,同样也可以解决旅游平台的问题。它的运行结果也和之前是一样的,有多种可能性。

  • 相关阅读:
    MySQL的内置函数
    Opencv——图像添加椒盐噪声、高斯滤波去除噪声原理及手写Python代码实现
    chrome 一些详细信息查找的地方
    论文解读(SimGRACE)《SimGRACE: A Simple Framework for Graph Contrastive Learning without Data Augmentation》
    python使用numpy的loadtext函数读取指定文本文件内容、读取后的数据格式为ndarray
    echarts折线图(其他图也是一样)设置tooltip自动滚动
    十五. 实战——mysql建库建表 字符集 和 排序规则
    c++三大概念要分清--重载,隐藏(重定义),覆盖(重写)
    Docker - 镜像
    掌动智能:卓越性能的API接口测试工具
  • 原文地址:https://blog.csdn.net/weixin_39795049/article/details/127839452