java 8 的 completablefuture 通过 forkjoinpool.commonpool() 默认使用工作窃取算法来提升效率。要利用这一特性,只需将耗时任务提交到公共线程池即可,无需手动配置。系统会自动处理任务的拆分与窃取,从而充分利用多核 cpu 资源。

如何提交任务以触发工作窃取
调用 supplyAsync() 或 runAsync() 且不指定自定义 Executor 时,任务会被自动分发到 ForkJoinPool.commonPool()。该池中的线程采用工作窃取机制,空闲线程会从其他忙碌线程的任务队列尾部窃取任务执行,从而减少线程阻塞和上下文切换开销。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(1000); } catch (InterruptedException e) {}
return "Result";
});
System.out.println(future.get());
}
}</string>
工作窃取在异步链式调用中的表现
当多个 CompletableFuture 通过 thenApply() 或 thenAccept() 链接时,后续任务同样由公共线程池调度。如果前一个任务耗时较长,后续任务会排队等待;若前一个任务快速完成,后续任务可能被立即窃取执行。这种动态调度使得整体执行时间接近最长分支的时间,而非所有任务时间的总和。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<string> f1 = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(500); } catch (InterruptedException e) {}
return "A";
});
CompletableFuture<string> f2 = f1.thenApply(result -> {
try { Thread.sleep(200); } catch (InterruptedException e) {}
return result + "B";
});
System.out.println(f2.get());
}
}</string></string>
公共线程池大小对性能的影响
ForkJoinPool.commonPool() 的并行度默认等于可用处理器数量减一。如果任务包含大量 I/O 操作,公共线程池可能因线程阻塞而耗尽,导致其他 CPU 密集型任务被延迟。此时应创建自定义 Executor 并传入 supplyAsync(),以避免工作窃取机制受到 I/O 阻塞的影响。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











