JDK 多线程系列--CompletableFuture类详解

异步计算

  • 所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。在 Java 语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需要等待计算结果。但调用者仍需要取线程的计算结果。

  • JDK5新增了Future接口,用于描述一个异步计算的结果。虽然 Future 以及相关使用方法提供了异步执行任务的能力,但是对于结果的获取却是很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然和我们的异步编程的初衷相违背,轮询的方式又会耗费无谓的 CPU 资源,而且也不能及时地得到计算结果。

  • 以前我们获取一个异步任务的结果可能是这样写的:

ExecutorService service = Executors.newSingleThreadExecutor();
        Future<Integer> future = service.submit(()->{
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 1;

        });

        System.out.println(future.get());
        System.out.println("finished!!");

Future 接口的局限性
Future接口可以构建异步应用,但依然有其局限性。它很难直接表述多个Future 结果之间的依赖性。实际开发中,我们经常需要达成以下目的:

  • 1.将两个异步计算合并为一个——这两个异步计算之间相互独立,同时第二个又依赖于第一个的结果。
  • 2.等待 Future 集合中的所有任务都完成。
  • 3.仅等待 Future集合中最快结束的任务完成(有可能因为它们试图通过不同的方式计算同一个值),并返回它的结果。
  • 4.通过编程方式完成一个Future任务的执行(即以手工设定异步操作结果的方式)。
  • 应对 Future 的完成事件(即当 Future 的完成事件发生时会收到通知,并能使用 Future 计算的结果进行下一步的操作,不只是简单地阻塞等待操作的结果)。
    函数式编程
    在这里插入图片描述
    CompletionStage
  • CompletionStage代表异步计算过程中的某一个阶段,一个阶段完成以后可能会触发另外一个阶段
  • 一个阶段的计算执行可以是一个Function,Consumer或者Runnable。比如:stage.thenApply(x -> square(x)).thenAccept(x -> System.out.print(x)).thenRun(() -> System.out.println())
  • 一个阶段的执行可能是被单个阶段的完成触发,也可能是由多个阶段一起触发。
    CompletableFuture

JDK1.8才新加入的一个实现类CompletableFuture,实现了Future<T>, CompletionStage<T>两个接口。

当一个Future可能需要显示地完成时,使用CompletionStage接口去支持完成时触发的函数和操作。

当两个及以上线程同时尝试完成、异常完成、取消一个CompletableFuture时,只有一个能成功。

CompletableFuture实现了CompletionStage接口的如下策略:

  • 1.为了完成当前的CompletableFuture接口或者其他完成方法的回调函数的线程,提供了非异步的完成操作。
  • 2.没有显式入参Executor的所有async方法都使用ForkJoinPool.commonPool()为了简化监视、调试和跟踪,所有生成的异步任务都是标记接口AsynchronousCompletionTask的实例。
  • 3.所有的CompletionStage方法都是独立于其他共有方法实现的,因此一个方法的行为不会受到子类中其他方法的覆盖。

CompletableFuture实现了Future接口的如下策略:

  • 1.CompletableFuture无法直接控制完成,所以cancel操作被视为是另一种异常完成形式。方法isCompletedExceptionally可以用来确定一个CompletableFuture是否以任何异常的方式完成。

  • 2.以一个CompletionException为例,方法get()get(long,TimeUnit)抛出一个ExecutionException,对应CompletionException。为了在大多数上下文中简化用法,这个类还定义了方法join()getNow,而不是直接在这些情况中直接抛出CompletionException

CompletableFuture中4个异步执行任务静态方法:

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return asyncSupplyStage(asyncPool, supplier);
    }
    
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) {
    return asyncSupplyStage(screenExecutor(executor), supplier);
}
    
public static CompletableFuture<Void> runAsync(Runnable runnable) {
    return asyncRunStage(asyncPool, runnable);
}
    
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) {
    return asyncRunStage(screenExecutor(executor), runnable);
}

其中supplyAsync用于有返回值的任务,runAsync则用于没有返回值的任务。Executor参数可以手动指定线程池,否则默认ForkJoinPool.commonPool()系统级公共线程池,
注意:这些线程都是Daemon线程,主线程结束Daemon线程不结束,只有JVM关闭时,生命周期终止。
CompletableFuture基本用法
创建CompletableFuture

 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return asyncSupplyStage(asyncPool, supplier);
    }
 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }
public static CompletableFuture<Void> runAsync(Runnable runnable) {
        return asyncRunStage(asyncPool, runnable);
    }  
public static CompletableFuture<Void> runAsync(Runnable runnable,
                                                   Executor executor) {
        return asyncRunStage(screenExecutor(executor), runnable);
    }      
    

thenApply

public <U> CompletableFuture<U> thenApply(
        Function<? super T,? extends U> fn) {
        return uniApplyStage(null, fn);
    }
public <U> CompletableFuture<U> thenApplyAsync(
        Function<? super T,? extends U> fn) {
        return uniApplyStage(asyncPool, fn);
    }

public <U> CompletableFuture<U> thenApplyAsync(
        Function<? super T,? extends U> fn, Executor executor) {
        return uniApplyStage(screenExecutor(executor), fn);
    }    

当前阶段正常完成以后执行,而且当前阶段的执行的结果会作为下一阶段的输入参数。thenApplyAsync默认是异步执行的。这里所谓的异步指的是不在当前线程内执行。
thenApply相当于回调函数(callback)

CompletableFuture.supplyAsync(()->1)
                    .thenApply(i->i+1)
                    .thenApply(i->i * i)
                    .whenComplete((r, e)->System.out.println(r));
        CompletableFuture.supplyAsync(()->"Hello")
                        .thenApply(s->s+" World")
                        .thenApply(String::toUpperCase);

thenAccept与thenRun
在这里插入图片描述

  • 可以看到,thenAccept和thenRun都是无返回值的。如果说thenApply是不停的输入输出的进行生产,那么thenAccept和thenRun就是在进行消耗。它们是整个计算的最后两个阶段。
    同样是执行指定的动作,同样是消耗,二者也有区别:

    • thenAccept接收上一阶段的输出作为本阶段的输入
    • thenRun根本不关心前一阶段的输出,根本不不关心前一阶段的计算结果,因为它不需要输入参数
      thenCombine整合两个计算结果
      在这里插入图片描述
      例如,此阶段与其它阶段一起完成,进而触发下一阶段:
CompletableFuture.supplyAsync(() -> "Hello").thenApply(s -> s + "World")
                .thenApply(String::toUpperCase)
                .thenCombine(CompletableFuture.completedFuture("Java"), (s1, s2) -> s1 + s2)
                .thenAccept(System.out::println);
//结果为:HELLOWORLDJava                

whenComplete

 String[] list = {"a","b","c"};
        List<CompletableFuture> resList = new ArrayList<CompletableFuture>();
        for (String str : list) {
            resList.add(CompletableFuture.supplyAsync(()->str).thenApply(e->e.toUpperCase()));
            
        }

        CompletableFuture.allOf(resList.toArray(new CompletableFuture[resList.size()]))
                    .whenComplete((r,e)->{
                        if(null == e){

                        }else{
                            throw new RuntimeException(e);
                        }
                    });

异常处理
CompletableFuture实现了Future接口,因此你可以像Future那样使用它。
其次,CompletableFuture并非一定要交给线程池执行才能实现异步,你可以像下面这样实现异步运行:

 @Test
    public void test1() throws InterruptedException, ExecutionException {

        CompletableFuture<String> future = new CompletableFuture<String>();
        new Thread(() -> {
            // 模拟执行耗时任务
            System.out.println("task doing...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 告诉completableFuture 任务已经完成
            future.complete("ok");
        }).start();
        // 获取任务结果,如果没有任务会一直阻塞等待
        String result = future.get();
        System.out.println("计算结果:" + result);

    }

如果没有意外,上面发的代码工作得很正常。但是,如果任务执行过程中产生了异常会怎样呢?

非常不幸,这种情况下你会得到一个相当糟糕的结果:异常会被限制在执行任务的线程的范围内,最终会杀死该线程,而这会导致等待get方法返回结果的线程永久地被阻塞。

客户端可以使用重载版本的get 方法,它使用一个超时参数来避免发生这样的情况。这是一种值得推荐的做法,你应该尽量在你的代码中添加超时判断的逻辑,避免发生类似的问题。

使用这种方法至少能防止程序永久地等待下去,超时发生时,程序会得到通知发生了TimeoutException 。不过,也因为如此,你不能确定执行任务的线程内到底发生了什么问题。

为了能获取任务线程内发生的异常,你需要使用
CompletableFuturecompleteExceptionally方法将导致CompletableFuture内发生问题的异常抛出。这样,当执行任务发生异常时,调用get()方法的线程将会收到一个 ExecutionException异常,该异常接收了一个包含失败原因的Exception 参数。

@Test
public void test2() throws ExecutionException, InterruptedException {
    CompletableFuture<String> completableFuture = new CompletableFuture<>();
    new Thread(() -> {
        // 模拟执行耗时任务
        System.out.println("task doing...");
        try {
            Thread.sleep(3000);
            int i = 1/0;
        } catch (Exception e) {
            // 告诉completableFuture任务发生异常了
            completableFuture.completeExceptionally(e);
        }
        // 告诉completableFuture任务已经完成
        completableFuture.complete("ok");
    }).start();
    // 获取任务结果,如果没有完成会一直阻塞等待
    String result = completableFuture.get();
    System.out.println("计算结果:" + result);
}

举个例子
JDK CompletableFuture 自带多任务组合方法allOf和anyOf
allOf是等待所有任务完成,构造后CompletableFuture完成
anyOf是只要有一个任务完成,构造后CompletableFuture就完成。

package com.viagra.java.concurrent.future;

import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: HASEE
 * @Description:
 * @Date: Created in 17:12 2019/4/19
 * @Modified By:
 */
public class CompletableFutureDemo2 {

	@Test
	public void test() {
		long start = System.currentTimeMillis();
		// 结果集
		List<String> list = new ArrayList<>();
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		List<Integer> taskList = Arrays.asList(2, 1, 3, 4, 5, 6, 7, 8, 9, 10);
		// 全流式处理转换成CompletableFuture[]+组装成一个无返回值CompletableFuture,
		//join等待执行完毕。返回结果whenComplete获取

		CompletableFuture[] cfs = taskList.stream()
				.map(integer -> CompletableFuture.supplyAsync(() -> calc(integer), executorService)
						.thenApply(h -> Integer.toString(h))
						.whenComplete((s, e) -> {
							System.out.println("任务" + s + "完成!result=" + s + ",异常 e=" + e + "," + new Date());
							list.add(s);
						})
				).toArray(CompletableFuture[]::new);

		// 封装后无返回值,必须自己whenComplete()获取
		CompletableFuture.allOf(cfs).join();
		System.out.println("list=" + list + ",耗时=" + (System.currentTimeMillis() - start));
	}

	public int calc(Integer i) {
		try {
			if (i == 1) {
				Thread.sleep(3000);// 任务1耗时3秒
			} else if (i == 5) {
				Thread.sleep(5000);// 任务5耗时5秒
			} else {
				Thread.sleep(1000);// 其它任务耗时1秒
			}
			System.out.println("task线程:" + Thread.currentThread().getName() + "任务i=" + i + ",完成!+" + new Date());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return i;
	}
}

结果:
在这里插入图片描述
一个完整的例子:

package multiThread.completableFutureTest;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author: HASEE
 * @Description: 20个简单例子
 * @Date: Created in 13:30 2019/4/20
 * @Modified By:
 */
public class CompletableFutureSimpleDemo {

	static Random random = new Random();

	static ExecutorService executor = Executors.newFixedThreadPool(3, new ThreadFactory() {
		int count = 1;

		@Override
		public Thread newThread(Runnable r) {
			return new Thread(r, "custom-executor-" + count++);
		}
	});


	public static void main(String[] args) {

		applyToEitherExample();
	}

	/**
	 * 以上代码用来启动异步计算,getNow(null)返回计算结果或者 null
	 */
	static void completedFutureExample() {
		CompletableFuture<String> cf = CompletableFuture.completedFuture("message");
		assertTrue(cf.isDone());
		assertEquals("message", cf.getNow(null));
	}
	// 运行简单的异步场景

	/**
	 * CompletableFuture 是异步执行方式;
	 * 使用 ForkJoinPool 实现异步执行,
	 * 这种方式使用了 daemon 线程执行 Runnable 任务。
	 */
	static void runAsyncExample() {
		CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> {
			assertTrue(Thread.currentThread().isDaemon());
			randomSleep();
		});
		assertFalse(cf.isDone());
		sleepEnough();
		assertTrue(cf.isDone());

	}

	//同步执行动作示例
	//在异步计算正常完成的前提下将执行动作(此处为转换成大写字母)
	static void thenApplyExample() {
		CompletableFuture<String> cf = CompletableFuture.completedFuture("message")
				.thenApply(s -> {
					assertFalse(Thread.currentThread().isDaemon());
					return s.toUpperCase();
				});
		assertEquals("MESSAGE", cf.getNow(null));
	}

	/**
	 * 相较thenApplyExample()的同步方式,以下代码实现了异步方式,
	 * 仅仅是在上面的代码里的多个方法增加"Async"这样的关键字。
	 */
	static void thenApplyAsyncExample() {
		CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(s -> {
			assertTrue(Thread.currentThread().isDaemon());
			randomSleep();
			return s.toUpperCase();
		});
		assertNull(cf.getNow(null));
		assertEquals("MESSAGE", cf.join());
	}

	//使用固定的线程池完成异步执行动作示例

	/**
	 * 我们可以通过使用线程池方式来管理异步动作申请,
	 * 以下代码基于固定的线程池,也是做一个大写字母转换动作
	 */
	public static void thenApplyAsyncWithExecutorExample() {
		CompletableFuture<String> cf = CompletableFuture.completedFuture("message").
				thenApplyAsync(s -> {
					assertTrue(Thread.currentThread().getName().startsWith("custom-executor-"));
					randomSleep();
					return s.toUpperCase();
				}, executor);
		assertNull(cf.getNow(null));
		assertEquals("MESSAGE", cf.join());
	}

	/**
	 * 作为消费者消费计算结果示例
	 * 假设我们本次计算只需要前一次的计算结果,而不需要返回本次计算结果,
	 * 那就有点类似于生产者(前一次计算)-消费者(本次计算)模式了
	 * 消费者是同步执行的,所以不需要在 CompletableFuture 里对结果进行合并。
	 */
	static void thenAcceptLastResultExample() {
		StringBuilder result = new StringBuilder();
		CompletableFuture.completedFuture("then Accept message")
				.thenAccept(s -> result.append(s));
		assertTrue("Result was empty", result.length() > 0);

	}

	/**
	 * 相较于thenAcceptLastResultExample()的同步方式,我们也对应有异步方式,代码如清单 11 所示。
	 */
	static void thenAcceptAsyncExample() {
		StringBuilder result = new StringBuilder();
		CompletableFuture<Void> cf = CompletableFuture.completedFuture("thenAcceptAsync message")
				.thenAcceptAsync(s -> result.append(s));
		cf.join();
		assertTrue("Result was empty", result.length() > 0);
	}

	/**
	 * 我们可以创建一个 CompletableFuture 接收两个异步计算的结果,下面代码首先创建了一个 String 对象,
	 * 接下来分别创建了两个 CompletableFuture 对象 cf1 和 cf2,
	 * f2 通过调用 applyToEither 方法实现我们的需求
	 */
	static void applyToEitherExample() {
		String original = "Message";
		CompletableFuture cf1 = CompletableFuture.completedFuture(original)
				.thenApplyAsync(s -> delayedUpperCase(s));
		CompletableFuture cf2 = cf1.applyToEither(
				CompletableFuture.completedFuture(original).thenApplyAsync(s -> delayedLowerCase(s)),
				s -> s + " from applyToEither");
		assertTrue(cf2.join().toString().endsWith(" from applyToEither"));
	}
	//如果我们想要使用applyToEitherExample()方法方式用于处理异步计算结果
	static void acceptEitherExample() {

		String original = "Message";
		StringBuilder result = new StringBuilder();
		CompletableFuture cf = CompletableFuture.completedFuture(original)
				.thenApplyAsync(s->delayedLowerCase(s))
				.acceptEither(CompletableFuture.completedFuture(original).
						thenApplyAsync(s->delayedLowerCase(s)),s->result.append(s).append("acceptEither"));
		cf.join();
		assertTrue("Result was empty", result.toString().endsWith("acceptEither"));
	}


	private static String delayedLowerCase(String s) {
		randomSleep();
		return s.toLowerCase();
	}

	private static String delayedUpperCase(String s) {
		randomSleep();
		return s.toUpperCase();
	}


	private static void randomSleep() {
		try {
			Thread.sleep(random.nextInt(1000));
		} catch (InterruptedException e) {
			// ...
		}
	}

	private static void sleepEnough() {
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// ...
		}
	}


}


参考:

https://www.cnblogs.com/cjsblog/p/9267163.html
https://blog.csdn.net/u011726984/article/details/79320004

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值