CompletableFuture是JDK1.8新增的一个异步执行任务类,可以发挥多核CPU的优势,也可以将任务并行执行,最后归并结果,下面是一个工具类,这个工具类使用在遍历集合处理数据或调用接口时,异步执行任务,最后归并任务,提升执行性能,具体代码如下。
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.CollectionUtils;import java.util.ArrayList;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); /** * 异步调用单个参数方法,有返回结果 * 例子: * CompletableFuturefuture = AsyncUtil.asyncCall((t)->{ * // do something ... * return result; * },t) * //阻塞获取结果 * AsyncUtil.get(future) * * 底层使用: * private static final Executor asyncPool = useCommonPool ? ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); * @param function Function * @param * @return */ public static CompletableFuture asyncCall(Function function,T t){ return supplyAsync(() -> function.apply(t)); } /** * 异步调用两个参数方法,有返回结果 * 例子: * CompletableFuture 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 * @return */ public static CompletableFuture asyncCall(BiFunction function, T t,U u){ return supplyAsync(() -> function.apply(t,u)); } /** * 获取异步结果中的值(阻塞等待结果) * @param future * @param * @return */ public static T get(CompletableFuture future){ if(future == null){ future = new CompletableFuture<>(); } 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 * @return 真实结果集合 */ public static List get(List > futures){ if(CollectionUtils.isEmpty(futures)){ futures = new ArrayList<>(); } List list = new ArrayList<>(futures.size()); //遍历获取结果集合 for (CompletableFuture 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; }}