CompletableFuture的5个大坑!

SpringBoot使用@Async注解8大坑点 SpringBoot中,@Async注解可以实现异步线程调用,用法简单,体验舒适。但是你一定碰到过异步调用不生效的情况,今天,我就列出90%的人都可能会遇到的8大坑点。这里面,我个人认为绝大多数人会遇到的坑点集中在没有配置自定义线程池、异步方法在同一个类中调用、事务不起作用这几个问题上。所以,万金油的写法还是专门定义一个AsyncService,将异步方法都写在里面,需要使用的时候,就在其他类将其注入即可。 阅读详情

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料: 

👉这是一个或许对你有用的开源项目

国产Star破10w的开源项目,前端包括管理后台、微信小程序,后端支持单体、微服务架构

RBAC权限、数据权限、SaaS多租户、商城、支付、工作流、大屏报表、ERP、CRM、AI大模型、IoT物联网等功能:

  • 多模块:https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • 微服务:https://gitee.com/zhijiantianya/yudao-cloud

  • 视频教程:https://doc.iocoder.cn

【国内首批】支持 JDK17/21+SpringBoot3、JDK8/11+Spring Boot2双版本 

来源:苏三说技术


前言

CompletableFuture在并发编程中非常实用,但如果用不好,也很容易踩坑。

今天这篇文章跟大家一起聊聊,CompletableFuture在使用过程中最常见的那些坑,希望对你会有所帮助。

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

一、CompletableFuture简介

有些小伙伴在工作中刚开始接触CompletableFuture时,可能会被它强大的功能所吸引。

确实,CompletableFuture为我们提供了非常优雅的异步编程方式,但正如武侠小说中的神兵利器,如果使用不当,反而会伤到自己。

CompletableFuture的基本用法

先来看一个简单的CompletableFuture使用示例:

public class BasicCompletableFutureDemo {
    
    public static void main(String[] args) throws Exception {
        // 简单的异步计算
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return"Hello, CompletableFuture!";
        });
        
        // 获取结果(阻塞)
        String result = future.get();
        System.out.println(result);
    }
}

看起来很简单对吧?但正是这种表面上的简单,掩盖了很多潜在的复杂性。

让我们通过一个架构图来理解CompletableFuture的完整生态:

现在,让我们开始深入探讨各个坑点。

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

二、线程池使用不当

有些小伙伴在使用CompletableFuture时,往往忽略了线程池的配置,这可能是最容易被忽视但影响最大的坑。

默认线程池的陷阱

public class ThreadPoolPitfall {
    
    // 危险的用法:大量使用默认线程池
    public void processBatchData(List<String> dataList) {
        List<CompletableFuture<String>> futures = new ArrayList<>();
        
        for (String data : dataList) {
            // 使用默认的ForkJoinPool.commonPool()
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                return processData(data);
            });
            futures.add(future);
        }
        
        // 等待所有任务完成
        CompletableFuture.allOf(fatures.toArray(new CompletableFuture[0]))
                        .join();
    }
    
    private String processData(String data) {
        // 模拟数据处理
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return data.toUpperCase();
    }
}

问题分析:

  • 默认线程池大小是CPU核心数-1

  • 在IO密集型任务中,这会导致大量任务排队等待

  • 如果任务提交速度 > 任务处理速度,会造成内存溢出

正确的线程池使用方式

public class ProperThreadPoolUsage {
    
    privatefinal ExecutorService ioBoundExecutor;
    privatefinal ExecutorService cpuBoundExecutor;
    
    public ProperThreadPoolUsage() {
        // IO密集型任务 - 使用较大的线程池
        this.ioBoundExecutor = new ThreadPoolExecutor(
            50, // 核心线程数
            100, // 最大线程数
            60L, TimeUnit.SECONDS, // 空闲线程存活时间
            new LinkedBlockingQueue<>(1000), // 工作队列
            new ThreadFactoryBuilder().setNameFormat("io-pool-%d").build(),
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
        
        // CPU密集型任务 - 使用较小的线程池
        this.cpuBoundExecutor = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(), // CPU核心数
            Runtime.getRuntime().availableProcessors() * 2,
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            new ThreadFactoryBuilder().setNameFormat("cpu-pool-%d").build(),
            new ThreadPoolExecutor.AbortPolicy()
        );
    }
    
    public CompletableFuture<String> processWithProperPool(String data) {
        return CompletableFuture.supplyAsync(() -> {
            // IO操作,使用IO线程池
            return fetchFromDatabase(data);
        }, ioBoundExecutor);
    }
    
    public CompletableFuture<String> computeWithProperPool(String data) {
        return CompletableFuture.supplyAsync(() -> {
            // CPU密集型计算,使用CPU线程池
            return heavyComputation(data);
        }, cpuBoundExecutor);
    }
    
    // 资源清理
    @PreDestroy
    public void destroy() {
        ioBoundExecutor.shutdown();
        cpuBoundExecutor.shutdown();
        try {
            if (!ioBoundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                ioBoundExecutor.shutdownNow();
            }
            if (!cpuBoundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                cpuBoundExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            ioBoundExecutor.shutdownNow();
            cpuBoundExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

线程池工作流程对比

三、异常为什么神秘消失了?

有些小伙伴在调试CompletableFuture时,经常会发现异常"神秘消失"了,这其实是CompletableFuture异常处理机制的一个特性。

异常丢失的典型案例

public class ExceptionDisappearance {
    
    public void testExceptionLost() {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 这里会抛出异常
            return dangerousOperation();
        });
        
        // 添加转换链
        CompletableFuture<String> resultFuture = future.thenApply(result -> {
            System.out.println("处理结果: " + result);
            return result + " processed";
        });
        
        try {
            // 这里不会抛出异常!
            String result = resultFuture.get();
            System.out.println("最终结果: " + result);
        } catch (Exception e) {
            // 异常被包装在ExecutionException中
            System.out.println("捕获到异常: " + e.getClass().getName());
            System.out.println("根本原因: " + e.getCause().getMessage());
        }
    }
    
    private String dangerousOperation() {
        thrownew RuntimeException("业务操作失败!");
    }
    
    // 更隐蔽的异常丢失
    public void testHiddenExceptionLoss() {
        CompletableFuture.supplyAsync(() -> {
            thrownew BusinessException("重要异常");
        }).thenAccept(result -> {
            // 如果上游有异常,这里不会执行
            System.out.println("处理结果: " + result);
        });
        
        // 程序继续执行,异常被忽略!
        System.out.println("程序正常结束,但异常丢失了!");
    }
    
    staticclass BusinessException extends RuntimeException {
        public BusinessException(String message) {
            super(message);
        }
    }
}

CompletableFuture异常处理机制

正确的异常处理方式

public class ProperExceptionHandling {
    
    // 方法1:使用exceptionally进行恢复
    public CompletableFuture<String> handleWithRecovery() {
        return CompletableFuture.supplyAsync(() -> {
            return riskyOperation();
        }).exceptionally(throwable -> {
            // 异常恢复
            System.err.println("操作失败,使用默认值: " + throwable.getMessage());
            return"default-value";
        });
    }
    
    // 方法2:使用handle统一处理
    public CompletableFuture<String> handleWithUnified() {
        return CompletableFuture.supplyAsync(() -> {
            return riskyOperation();
        }).handle((result, throwable) -> {
            if (throwable != null) {
                // 处理异常
                System.err.println("操作异常: " + throwable.getMessage());
                return"error-value";
            }
            return result + "-processed";
        });
    }
    
    // 方法3:使用whenComplete进行副作用处理
    public CompletableFuture<Void> handleWithSideEffect() {
        return CompletableFuture.supplyAsync(() -> {
            return riskyOperation();
        }).whenComplete((result, throwable) -> {
            if (throwable != null) {
                // 记录日志、发送告警等
                logError(throwable);
                sendAlert(throwable);
            } else {
                // 正常业务处理
                processResult(result);
            }
        });
    }
    
    // 方法4:组合操作中的异常处理
    public CompletableFuture<String> handleInComposition() {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            return operation1();
        });
        
        CompletableFuture<String> future2 = future1.thenCompose(result1 -> {
            return CompletableFuture.supplyAsync(() -> {
                return operation2(result1);
            });
        });
        
        // 在整个链的末尾处理异常
        return future2.exceptionally(throwable -> {
            Throwable rootCause = getRootCause(throwable);
            if (rootCause instanceof BusinessException) {
                return"business-fallback";
            } elseif (rootCause instanceof TimeoutException) {
                return"timeout-fallback";
            } else {
                return"unknown-error";
            }
        });
    }
    
    private void logError(Throwable throwable) {
        // 记录错误日志
        System.err.println("错误记录: " + throwable.getMessage());
    }
    
    private void sendAlert(Throwable throwable) {
        // 发送告警
        System.out.println("发送告警: " + throwable.getMessage());
    }
    
    private Throwable getRootCause(Throwable throwable) {
        Throwable cause = throwable;
        while (cause.getCause() != null) {
            cause = cause.getCause();
        }
        return cause;
    }
}

四、回调地狱:当异步变成异痛

有些小伙伴在复杂业务场景中使用CompletableFuture时,很容易陷入回调地狱,代码变得难以理解和维护。

回调地狱的典型案例

public class CallbackHell {
    
    public CompletableFuture<String> processUserOrder(String userId) {
        return getUserInfo(userId)
            .thenCompose(userInfo -> {
                return getOrderHistory(userInfo.getId())
                    .thenCompose(orderHistory -> {
                        return calculateDiscount(userInfo, orderHistory)
                            .thenCompose(discount -> {
                                return createOrder(userInfo, discount)
                                    .thenCompose(order -> {
                                        return sendConfirmation(userInfo, order);
                                    });
                            });
                    });
            });
    }
    
    // 上述代码的"平铺"版本,同样难以阅读
    public CompletableFuture<String> processUserOrderFlat(String userId) {
        return getUserInfo(userId)
            .thenCompose(userInfo -> getOrderHistory(userInfo.getId()))
            .thenCompose(orderHistory -> getUserInfo(userId))
            .thenCompose(userInfo -> calculateDiscount(userInfo, orderHistory))
            .thenCompose(discount -> getUserInfo(userId))
            .thenCompose(userInfo -> createOrder(userInfo, discount))
            .thenCompose(order -> getUserInfo(userId))
            .thenCompose(userInfo -> sendConfirmation(userInfo, order));
    }
}

结构化异步编程解决方案

public class StructuredAsyncProgramming {
    
    // 定义业务数据类
    @Data
    @AllArgsConstructor
    publicstaticclass OrderContext {
        private String userId;
        private UserInfo userInfo;
        private List<Order> orderHistory;
        private Discount discount;
        private Order order;
        private String result;
    }
    
    public CompletableFuture<String> processUserOrderStructured(String userId) {
        OrderContext context = new OrderContext(userId, null, null, null, null, null);
        
        return getUserInfo(context.getUserId())
            .thenCompose(userInfo -> {
                context.setUserInfo(userInfo);
                return getOrderHistory(userInfo.getId());
            })
            .thenCompose(orderHistory -> {
                context.setOrderHistory(orderHistory);
                return calculateDiscount(context.getUserInfo(), orderHistory);
            })
            .thenCompose(discount -> {
                context.setDiscount(discount);
                return createOrder(context.getUserInfo(), discount);
            })
            .thenCompose(order -> {
                context.setOrder(order);
                return sendConfirmation(context.getUserInfo(), order);
            })
            .thenApply(result -> {
                context.setResult(result);
                return result;
            })
            .exceptionally(throwable -> {
                // 统一异常处理
                return handleOrderError(context, throwable);
            });
    }
    
    // 使用thenCombine处理并行任务
    public CompletableFuture<UserProfile> getUserProfile(String userId) {
        CompletableFuture<UserInfo> userInfoFuture = getUserInfo(userId);
        CompletableFuture<List<Order>> orderHistoryFuture = getOrderHistory(userId);
        CompletableFuture<List<Address>> addressesFuture = getUserAddresses(userId);
        
        return userInfoFuture.thenCombine(orderHistoryFuture, (userInfo, orders) -> {
            returnnew UserProfile(userInfo, orders, null);
        }).thenCombine(addressesFuture, (profile, addresses) -> {
            profile.setAddresses(addresses);
            return profile;
        });
    }
    
    // 使用allOf处理多个独立任务
    public CompletableFuture<Map<String, Object>> getDashboardData(String userId) {
        CompletableFuture<UserInfo> userInfoFuture = getUserInfo(userId);
        CompletableFuture<List<Order>> ordersFuture = getOrderHistory(userId);
        CompletableFuture<List<Notification>> notificationsFuture = getNotifications(userId);
        CompletableFuture<Preferences> preferencesFuture = getPreferences(userId);
        
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
            userInfoFuture, ordersFuture, notificationsFuture, preferencesFuture
        );
        
        return allFutures.thenApply(v -> {
            Map<String, Object> dashboard = new HashMap<>();
            try {
                dashboard.put("userInfo", userInfoFuture.get());
                dashboard.put("orders", ordersFuture.get());
                dashboard.put("notifications", notificationsFuture.get());
                dashboard.put("preferences", preferencesFuture.get());
            } catch (Exception e) {
                thrownew CompletionException(e);
            }
            return dashboard;
        });
    }
}

异步编程模式对比

更推荐的方案:

五、内存泄漏:隐藏的资源消耗者

有些小伙伴可能没有意识到,不当使用CompletableFuture会导致内存泄漏,特别是在长时间运行的应用中。

内存泄漏的常见场景

public class MemoryLeakDemo {
    
    privatefinal Map<String, CompletableFuture<String>> cache = new ConcurrentHashMap<>();
    
    // 场景1:无限增长的缓存
    public CompletableFuture<String> getDataWithLeak(String key) {
        return cache.computeIfAbsent(key, k -> {
            return CompletableFuture.supplyAsync(() -> fetchData(k));
        });
    }
    
    // 场景2:未完成的Future积累
    public void processWithUnfinishedFutures() {
        for (int i = 0; i < 100000; i++) {
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                // 模拟长时间运行或阻塞的任务
                try {
                    Thread.sleep(Long.MAX_VALUE); // 几乎永久阻塞
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return"result";
            });
            // future永远不会完成,但一直存在于内存中
        }
    }
    
    // 场景3:循环引用
    publicclass TaskManager {
        private CompletableFuture<String> currentTask;
        private String status = "INIT";
        
        public void startTask() {
            currentTask = CompletableFuture.supplyAsync(() -> {
                // 任务持有Manager的引用
                while (!"COMPLETED".equals(status)) {
                    // 处理任务
                    processTask();
                }
                return"done";
            });
        }
        
        // Manager也持有任务的引用
        public CompletableFuture<String> getCurrentTask() {
            return currentTask;
        }
    }
}

内存泄漏检测和预防

public class MemoryLeakPrevention {
    
    privatefinal Cache<String, CompletableFuture<String>> cache;
    
    public MemoryLeakPrevention() {
        // 使用Guava Cache自动清理
        this.cache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(10, TimeUnit.MINUTES)
            .removalListener((RemovalListener<String, CompletableFuture<String>>) notification -> {
                if (notification.getCause() == RemovalCause.SIZE || 
                    notification.getCause() == RemovalCause.EXPIRED) {
                    // 取消未完成的任务
                    CompletableFuture<String> future = notification.getValue();
                    if (!future.isDone()) {
                        future.cancel(true);
                    }
                }
            })
            .build();
    }
    
    // 安全的缓存用法
    public CompletableFuture<String> getDataSafely(String key) {
        try {
            return cache.get(key, () -> {
                CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> fetchData(key));
                
                // 添加超时控制
                return future.orTimeout(30, TimeUnit.SECONDS)
                           .exceptionally(throwable -> {
                               // 发生异常时从缓存中移除
                               cache.invalidate(key);
                               return"fallback-data";
                           });
            });
        } catch (ExecutionException e) {
            thrownew RuntimeException(e);
        }
    }
    
    // 使用WeakReference避免循环引用
    publicstaticclass SafeTaskManager {
        private WeakReference<CompletableFuture<String>> currentTaskRef;
        
        public void startTask() {
            CompletableFuture<String> task = CompletableFuture.supplyAsync(() -> {
                return performTask();
            });
            
            currentTaskRef = new WeakReference<>(task);
            
            // 任务完成后自动清理
            task.whenComplete((result, error) -> {
                currentTaskRef = null;
            });
        }
    }
    
    // 监控和诊断工具
    public void monitorFutures() {
        // 定期检查未完成的Future
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                int unfinishedCount = 0;
                for (CompletableFuture<?> future : cache.asMap().values()) {
                    if (!future.isDone()) {
                        unfinishedCount++;
                        // 记录长时间运行的任务
                        if (future.isDoneExceptionally()) {
                            // 处理异常任务
                            handleExceptionalFuture(future);
                        }
                    }
                }
                
                if (unfinishedCount > 100) {
                    // 发出警告
                    System.err.println("警告: 有 " + unfinishedCount + " 个未完成的任务");
                }
            }
        }, 0, 60000); // 每分钟检查一次
    }
    
    private void handleExceptionalFuture(CompletableFuture<?> future) {
        // 处理异常Future,避免它们一直存在
        future.exceptionally(throwable -> {
            // 记录异常日志
            System.err.println("任务异常: " + throwable.getMessage());
            returnnull;
        });
    }
}

内存泄漏检测流程

六、超时控制缺失

有些小伙伴在使用CompletableFuture时,经常会忘记设置超时控制,这可能导致线程永远阻塞。

超时问题的严重性

public class TimeoutPitfalls {
    
    // 危险的代码:没有超时控制
    public String dangerousGet() {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟网络问题导致的无限阻塞
            return blockingNetworkCall();
        });
        
        try {
            // 如果任务永远不完成,这里会永远阻塞
            return future.get();
        } catch (Exception e) {
            return"error";
        }
    }
    
    // 资源泄漏的示例
    public void resourceLeakExample() {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        
        for (int i = 0; i < 100; i++) {
            CompletableFuture.runAsync(() -> {
                try {
                    // 长时间运行的任务
                    Thread.sleep(Long.MAX_VALUE);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }, executor);
        }
        
        // 线程池中的线程都被占用,无法执行新任务
    }
    
    private String blockingNetworkCall() {
        // 模拟网络问题
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return"response";
    }
}

完整的超时控制方案

public class CompleteTimeoutSolution {
    
    privatefinal ScheduledExecutorService timeoutExecutor;
    
    public CompleteTimeoutSolution() {
        this.timeoutExecutor = Executors.newScheduledThreadPool(2);
    }
    
    // 方法1:使用orTimeout(Java 9+)
    public CompletableFuture<String> withOrTimeout() {
        return CompletableFuture.supplyAsync(() -> {
            return externalServiceCall();
        }).orTimeout(5, TimeUnit.SECONDS) // 5秒超时
          .exceptionally(throwable -> {
              if (throwable instanceof TimeoutException) {
                  return"timeout-fallback";
              }
              return"error-fallback";
          });
    }
    
    // 方法2:使用completeOnTimeout(Java 9+)
    public CompletableFuture<String> withCompleteOnTimeout() {
        return CompletableFuture.supplyAsync(() -> {
            return externalServiceCall();
        }).completeOnTimeout("timeout-default", 3, TimeUnit.SECONDS);
    }
    
    // 方法3:手动超时控制(Java 8兼容)
    public CompletableFuture<String> withManualTimeout() {
        CompletableFuture<String> taskFuture = CompletableFuture.supplyAsync(() -> {
            return externalServiceCall();
        });
        
        CompletableFuture<String> timeoutFuture = new CompletableFuture<>();
        
        // 设置超时
        timeoutExecutor.schedule(() -> {
            timeoutFuture.completeExceptionally(new TimeoutException("操作超时"));
        }, 5, TimeUnit.SECONDS);
        
        // 哪个先完成就返回哪个
        return taskFuture.applyToEither(timeoutFuture, Function.identity())
                       .exceptionally(throwable -> {
                           if (throwable instanceof TimeoutException) {
                               return"manual-timeout-fallback";
                           }
                           return"other-error-fallback";
                       });
    }
    
    // 方法4:分层超时控制
    public CompletableFuture<String> withLayeredTimeout() {
        return CompletableFuture.supplyAsync(() -> {
            return phase1Operation();
        }).orTimeout(2, TimeUnit.SECONDS)
          .thenCompose(phase1Result -> {
              return CompletableFuture.supplyAsync(() -> {
                  return phase2Operation(phase1Result);
              }).orTimeout(3, TimeUnit.SECONDS);
          })
          .thenCompose(phase2Result -> {
              return CompletableFuture.supplyAsync(() -> {
                  return phase3Operation(phase2Result);
              }).orTimeout(5, TimeUnit.SECONDS);
          })
          .exceptionally(throwable -> {
              Throwable rootCause = getRootCause(throwable);
              if (rootCause instanceof TimeoutException) {
                  // 根据超时阶段提供不同的降级策略
                  return"timeout-in-phase";
              }
              return"general-fallback";
          });
    }
    
    // 方法5:可配置的超时策略
    public CompletableFuture<String> withConfigurableTimeout(String operationType) {
        TimeoutConfig config = getTimeoutConfig(operationType);
        
        return CompletableFuture.supplyAsync(() -> {
            return performOperation(operationType);
        }).orTimeout(config.getTimeout(), config.getTimeUnit())
          .exceptionally(throwable -> {
              return config.getFallbackStrategy().apply(throwable);
          });
    }
    
    @PreDestroy
    public void destroy() {
        timeoutExecutor.shutdown();
        try {
            if (!timeoutExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                timeoutExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            timeoutExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
    
    // 超时配置类
    @Data
    publicstaticclass TimeoutConfig {
        privatefinallong timeout;
        privatefinal TimeUnit timeUnit;
        privatefinal Function<Throwable, String> fallbackStrategy;
    }
    
    private TimeoutConfig getTimeoutConfig(String operationType) {
        switch (operationType) {
            case"fast":
                returnnew TimeoutConfig(1, TimeUnit.SECONDS, 
                    t -> "fast-timeout");
            case"normal":
                returnnew TimeoutConfig(5, TimeUnit.SECONDS,
                    t -> "normal-timeout");
            case"slow":
                returnnew TimeoutConfig(30, TimeUnit.SECONDS,
                    t -> "slow-timeout");
            default:
                returnnew TimeoutConfig(10, TimeUnit.SECONDS,
                    t -> "default-timeout");
        }
    }
}

超时控制策略

总结

通过上面的详细分析,我们可以看到CompletableFuture虽然强大,但也确实存在不少陷阱。

最后的建议

  1. 理解原理 :不要只是机械地使用API,要理解CompletableFuture的工作原理

  2. 适度使用 :不是所有场景都需要异步,同步代码更简单易懂

  3. 测试覆盖 :异步代码的测试很重要,要覆盖各种边界情况

  4. 监控告警 :在生产环境中要有完善的监控和告警机制

  5. 持续学习 :关注Java并发编程的新特性和最佳实践

记住,工具是为了提高生产力,而不是制造问题。

掌握了这些避坑技巧,CompletableFuture将成为你手中强大的并发编程利器!


欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,“长按”或“扫描”下方二维码噢:

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
SpringBoot单元测试进阶:Mockito与JUnit5的23个高频场景实战 单元测试是保障软件质量与可维护性的基础实践,其核心在于隔离被测单元与外部依赖,聚焦业务逻辑验证。通过模拟(Mocking)技术,开发者可以创建可控的测试环境,避免数据库、网络等外部因素干扰,从而提升测试执行速度与稳定性。在Java生态中,JUnit5提供了现代化的测试框架,而Mockito作为主流模拟库,能够高效模拟对象行为、验证交互过程。结合SpringBoot项目,这些技术显著提升了测试效率与代码质量,尤其适用于微服务架构下的组件测试。本文围绕Mockito与JUnit5,系统解析了参数匹配、静态方法模 阅读详情

相关推荐

移动硬盘报错0x80070570?5分钟搞定CHKDSK修复(附详细参数说明)

本文针对移动硬盘报错0x80070570问题,提供了详细的CHKDSK修复方法。通过5分钟核心修复流程,指导用户使用系统自带工具快速修复文件系统逻辑错误,恢复硬盘访问。文章还深入解析了CHKDSK参数,并提供了备选数据恢复方案与日常防护建议。

app77的博客 236

CompletableFuture的5大坑!

摘要: 本文深入探讨了Java中CompletableFuture的5大使用陷阱。首先介绍了默认线程池的隐患,指出其不适合IO密集型任务且可能导致内存溢出,并给出了正确配置线程池的方案。其次分析了异常"神秘消失"问题,这是由于CompletableFuture的异常处理机制导致异常被包装在ExecutionException中。文章通过代码示例对比了错误和正确用法,并附上线程池工作流程对比图,帮助开发者避免这些常见陷阱。

IT枫斗者的博客 1586

2.13寸电子墨水屏HINK-E0213+esp8266

很久以前买的一块电子墨水屏,运气很好,这个型号HINK-E0213资料很全,而且微雪官网也有相关电路资料等。

梦境虽美,却不长. 3005

CompletableFuture六大坑

然而,在实际应用中,许多开发者常常会踩到一些"暗坑",导致程序出现各种难以排查的问题。CompletableFuture 的回调操作默认在同一个线程池中执行,如果在回调中执行阻塞操作,就会占用线程池中的线程资源,导致线程无法及时处理其他异步任务,进而影响整个异步架构的性能。CompletableFuture 的回调操作默认在同一个线程池中执行,如果在回调中执行阻塞操作,就会占用线程池中的线程资源,导致线程无法及时处理其他异步任务,进而影响整个异步架构的性能。阻塞操作:隔离阻塞任务,避免影响非阻塞任务。

weixin_42774617的博客 981

Win10环境下VS2019离线部署OnnxRuntime的完整指南

本文提供了在Windows 10系统下,为Visual Studio 2019进行OnnxRuntime离线部署的完整教程。针对网络受限环境,详细讲解了如何获取正确的离线安装包、配置本地NuGet源,并逐步指导项目配置与测试,确保AI模型在C++环境中顺利运行。

weixin_29205061的博客 401

用Frida-RPC搞定大麦App最新版签名:一个脚本解决x-sign和x-mini-wua

本文深入解析大麦App最新版签名机制(x-sign和x-mini-wua),详细介绍如何利用Frida-RPC技术开发稳定脚本获取签名参数。通过实战案例展示Java上下文切换、参数序列化等关键技术解决方案,为安全研究和技术验证提供可靠方案。

weixin_42525738的博客 648

Java 8 的异步编程利器 CompletableFuture 详解

的get()方法是阻塞的,我们一般建议使用。并且一般建议使用自定义线程池。但是如果线程池拒绝策略是或者,当线程池饱和时,会直接丢弃任务,不会抛弃异常。因此建议,线程池策略最好使用,然后耗时的异步线程,做好线程池隔离哈。

qq_39093474的博客 831

避开地图定位的坑:手把手教你处理GCJ-02和WGS-84坐标转换(2023最新版)

本文深入解析了GCJ-02与WGS-84坐标系转换的核心原理与常见误区,提供了详细的代码实现与精度控制方法。针对地图定位开发中的实际痛点,文章重点阐述了如何通过迭代逼近法实现高精度坐标转换,并给出了误差测试与业务场景下的工程实践指南,帮助开发者有效规避定位漂移等问题。

lstm7chronicler的博客 1172

线程池遇到父子任务,有大坑,要注意!

这个代码的逻辑非常简单,首先我们搞了一个线程池,然后起一个 for 循环往线程池里面仍了 5 个任务,这是核心逻辑。从日志输出来看,任务 2 需要处理的两个数据,确实是在不同的异步线程中处理数据,也实现了我的需求。这个地方从数据库捞出来的数据,它们之间是没有依赖关系的,也就是说它们之间也是可以并行执行的。对于这几个任务,我们的这个自定义线程池处理起来,不能说得心应手吧,至少也是手拿把掐。即子任务全部完成之后,父任务才能算执行完成,这样统计出来的时间才是准确的。

IR8468vbo的博客 224

别再盲调PID了!手把手教你用VOFA+实时可视化电机速度曲线(附STM32F4源码)

本文详细介绍了如何使用VOFA+工具实现PID参数的可视化调试,帮助开发者从盲调转向精准调优。通过实时可视化电机速度曲线,结合STM32F4源码示例,展示了如何高效调试Kp、Ki、Kd参数,解决响应慢、超调等常见问题,大幅提升电机控制系统的性能。

weixin_28366475的博客 130

Python 爬虫实战:豆瓣 / IMDB 电影数据抓取(评分 + 剧情 + 演员阵容结构化处理)

在数据为王的时代,电影数据是进行市场分析、推荐系统构建和学术研究的重要资源。豆瓣和 IMDB 作为国内外最具影响力的电影评分和资讯网站,包含了海量高质量的电影数据。本文将带领你从零开始,构建一个健壮的 Python 爬虫,用于抓取豆瓣和 IMDB 的电影信息,并将其中的非结构化数据(如剧情简介、演员列表)进行清洗和结构化处理,最终存储到便于分析的结构化文件(如 CSV)中。

yansideyucsdn的博客 957

5分钟了解SpringBoot使用@Async注解8大坑点

SpringBoot中,@Async注解可以实现异步线程调用,用法简单,体验舒适。但是你一定碰到过异步调用不生效的情况,今天,我就列出90%的人都可能会遇到的8大坑点。

xiangyangsanren的专栏 452

18、改进的LSTM用于污染物浓度预测

本文探讨了改进的长短期记忆网络(MLSTM)在空气污染预测中的应用,重点分析了其对印度泰米尔纳德邦五个城市(金奈、塞勒姆、哥印拜陀、马杜赖和图蒂科林)的PM2.5、PM10、SO2和NO2四种污染物浓度的预测效果。通过与传统LSTM模型的对比实验,结果显示MLSTM在预测准确性和执行效率方面均优于LSTM。研究结果表明,MLSTM在空气质量预测领域具有较高的应用潜力,可为环境保护和空气质量管理提供有力支持。

j0k1l2m3n的博客 175

CompletableFuture实战:从Future到异步编排,线程池与异常处理全解析

在Java并发编程中,Future接口虽然能提交异步任务,但调用get()时会阻塞线程,且多个任务之间难以组合,本质上是同步等待。CompletableFuture基于CompletionStage模型,将异步任务拆解为可组合的流水线阶段,支持串行依赖、并行合并、竞速聚合等编排模式。它不仅能解决Future的硬伤,更能通过thenApply、thenCompose、allOf等API,让复杂异步逻辑变得清晰可控。正确使用CompletableFuture的关键在于理解线程池的选型——默认的ForkJoinP

weixin_33858485的博客 533

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

CompletableFuture性能优化:从串行到并行接口耗时降低3倍

在Java异步编程中,CompletableFuture通过回调链、工作窃取线程池和零拷贝组合操作,显著提升IO密集型场景的吞吐量。其核心原理在于用非阻塞等待替代线程挂起,并利用ForkJoinPool的work-stealing算法提高CPU利用率。技术价值体现在接口响应时间从串行累加降至最慢任务耗时,QPS可提升数倍。典型应用场景包括订单查询、商品详情聚合等微服务编排。但需注意默认线程池的阻塞风险,建议自定义线程池并合理配置超时。本文深入拆解CompletableFuture的性能来源,结合实操案例与避

weixin_31364787的博客 54

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Java线程池实战:核心原理与配置优化指南

线程池作为Java并发编程的核心组件,通过复用线程资源显著提升系统吞吐量。其底层基于生产者-消费者模型,通过ThreadPoolExecutor的七大参数实现资源管控,包括核心线程数、任务队列和拒绝策略等关键配置。在IO密集型场景中,合理设置线程数可避免磁盘/网络阻塞;计算密集型任务则需严格匹配CPU核数。典型应用包括Web服务请求处理、大数据计算任务分发等场景,配合JMX监控和自定义拒绝策略可构建高可靠系统。文章结合JUC线程池的OOM防护和性能调优实战,详解LinkedBlockingQueue与Arr

weixin_34049948的博客 524

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

多线程编程优秀文章

1 优秀文章合集 1.1 学习CompletionService ,以及它的思想 送你一个并发编程的奇淫巧技,舒服的很...

iNiBuBian的博客 384

@Async异步线程池失效排查与正确配置:从代理原理到实战调优

在Spring应用开发中,异步编程是提升接口吞吐量的常用手段,而@Async注解则是实现方法级异步最直接的入口。很多开发者以为加上注解就能自动获得异步能力,却常常遇到任务仍在原线程执行、线程池资源失控或事务边界错乱等问题。这背后的核心在于Spring AOP代理机制:只有通过容器注入的代理对象调用方法,异步拦截器才会介入,而同类内部调用、private方法或final类都会导致代理失效。理解代理原理后,还需掌握默认线程池的局限性,比如SimpleAsyncTaskExecutor在高并发下会创建海量线程,S

weixin_30899023的博客 263
上一篇: 一款被低估的插件:IDEA+JProfiler=性能分析神器
下一篇: IntelliJ IDEA 2026.1 EAP 3 发布:被开发者催了 6 年,这个细节终于修了!
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值