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);
/**
* 异步调用单个参数方法,有返回结果
* 例子:
* 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){
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 <T>
* @return 真实结果集合
*/
public static <T> List<T> get(List<CompletableFuture<T>> futures){
if(CollectionUtils.isEmpty(futures)){
futures = new ArrayList<>();
}
List<T> list = new ArrayList<>(futures.size());
//遍历获取结果集合
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;
}
}