Java异步编程探索之CompletableFuture

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * 异步执行工具类 继承 CompletableFuture
 * @author yangchangkui
 */
public class AsyncUtil extends CompletableFuture {

    private static final Logger logger = LoggerFactory.getLogger(AsyncUtil.class);


    /**
     * 异步调用单个参数方法,有返回结果
     * 例子:
     * CompletableFuture<R> future = AsyncUtil.asyncCall((t)->{
     *      // do something ...
     *      return result;
     *  },t)
     * //阻塞获取结果
     * AsyncUtil.get(future)
     *
     * 底层使用:
     *    private static final Executor asyncPool = useCommonPool ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
     * @param function Function<T,R>
     * @param <T>
     * @return
     */
    public static  <T,R> CompletableFuture<R> asyncCall(Function<T,R> function,T t){
        return supplyAsync(() -> function.apply(t));
    }


    /**
     * 异步调用两个参数方法,有返回结果
     * 例子:
     * CompletableFuture<R> future = AsyncUtil.asyncCall((t,u) -> {
     *          //do something ...
     *
     *          return result;
     *      }, t,u);
     *
     * //阻塞获取结果
     * AsyncUtil.get(future)
     *
     * 底层使用:
     *     private static final Executor asyncPool = useCommonPool ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
     * @param function
     * @param <T>
     * @return
     */
    public static  <T, U, R> CompletableFuture<R> asyncCall(BiFunction<T, U, R> function, T t,U u){
        return supplyAsync(() -> function.apply(t,u));
    }


    /**
     * 获取异步结果中的值(阻塞等待结果)
     * @param future
     * @param <T>
     * @return
     */
    public static  <T> T get(CompletableFuture<T> future){
        try {
            return future.get();
        } catch (InterruptedException ie) {
            logger.error("future.get interruptedException",ie);
        } catch (ExecutionException ee) {
            logger.error("future.get executionException",ee);
        }
        return null;
    }





    /**
     * 获取结果异步集合中的结果集合(阻塞等待结果)
     * @param futures
     * @param <T>
     * @return 真实结果集合
     */
    public static  <T> List<T> get(List<CompletableFuture<T>> futures){
        List<T> list = CollectionUtil.createArrayList();

        //遍历获取结果集合
        for (CompletableFuture<T> future : futures) {
            try {
                T t = future.get();
                list.add(t);
            } catch (InterruptedException ie) {
                logger.error("future.get interruptedException",ie);
            } catch (ExecutionException ee) {
                logger.error("future.get executionException",ee);
            }
        }
        return list;
    }


}

  这个工具使用在遍历集合处理数据或调用接口的使用,异步执行任务,最后归并任务,提升执行性能。

上一篇:有了 CompletableFuture,使得异步编程没有那么难了!


下一篇:廖雪峰Java11多线程编程-3高级concurrent包-8CompletableFuture