写一个utils方法,用于从CompletableFuture获取结果,要求在指定时间内返回,如果任务未完成,返回null
- User
写一个utils方法,用于从CompletableFuture获取结果,要求在指定时间内返回,如果任务未完成,返回null
Assistant
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FutureUtils { private static final Logger log = LoggerFactory.getLogger(FutureUtils.class); /** * 从 CompletableFuture 获取结果,如果在指定时间内任务未完成,则返回 null。 * 如果在获取结果过程中发生异常,也会返回 null 并记录错误日志。 * * @param future 要获取结果的 CompletableFuture * @param timeout 超时时间 * @param unit 超时时间单位 * @param <T> CompletableFuture 的结果类型 * @return CompletableFuture 的结果,如果在指定时间内未完成或发生异常,则返回 null */ public static <T> T getResultWithTimeout(CompletableFuture<T> future, long timeout, TimeUnit unit) { try { return future.get(timeout, unit); } catch (TimeoutException e) { log.warn("任务超时,在 {} {} 内未完成。", timeout, unit, e); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); // 恢复中断状态 log.error("任务被中断。", e); return null; } catch (ExecutionException e) { log.error("任务执行发生异常。", e); return null; } catch (Exception e) { log.error("发生未知异常。", e); return null; } } // 可以添加一些测试代码,以验证方法的正确性 public static void main(String[] args) throws InterruptedException { // 示例 1:快速完成的任务 CompletableFuture<String> fastFuture = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(100); // 模拟耗时操作 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "快速结果"; }); String fastResult = getResultWithTimeout(fastFuture, 1, TimeUnit.SECONDS); System.out.println("快速结果: " + fastResult); // 预期输出:快速结果: 快速结果 // 示例 2:超时的任务 CompletableFuture<String> slowFuture = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); // 模拟耗时操作 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "慢速结果"; }); String slowResult = getResultWithTimeout(slowFuture, 1, TimeUnit.SECONDS); System.out.println("慢速结果: " + slowResult); // 预期输出:慢速结果: null // 示例 3:异常任务 CompletableFuture<String> exceptionFuture = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("模拟异常"); }); String exceptionResult = getResultWithTimeout(exceptionFuture, 1, TimeUnit.SECONDS); System.out.println("异常结果: " + exceptionResult); // 预期输出:异常结果: null //清理线程池,避免main方法无法退出 Thread.sleep(3000); // 等待足够的线程池任务完成,仅用于测试 System.out.println("测试完成."); } }代码解释:
-
getResultWithTimeout(CompletableFuture<T> future, long timeout, TimeUnit unit)方法:- 接收一个
CompletableFuture,一个超时时间timeout,以及一个时间单位unit作为输入。 - 使用
future.get(timeout, unit)尝试在指定时间内获取CompletableFuture的结果。 - 异常处理:
TimeoutException: 如果在指定时间内任务未完成,抛出TimeoutException,记录warn级别的日志,并返回null。InterruptedException: 如果获取结果的过程中线程被中断,抛出InterruptedException,恢复中断状态(Thread.currentThread().interrupt()),记录error级别的日志,并返回null。ExecutionException: 如果CompletableFuture内部执行过程中发生了异常,抛出ExecutionException,记录error级别的日志,并返回null。Exception: 捕获其他所有异常,记录error级别的日志,并返回null。 这是一个兜底的异常处理方式.
- 接收一个
-
日志记录: 使用
slf4j记录日志,以便在生产环境中进行问题排查。 日志级别根据异常类型设置,TimeoutException使用warn级别,其余使用error级别。 -
单元测试 (
main方法):- 提供了三个示例,演示了
getResultWithTimeout方法在不同情况下的行为:- 快速完成的任务:
fastFuture在超时时间内完成。 - 超时的任务:
slowFuture在超时时间内未完成。 - 异常的任务:
exceptionFuture内部抛出异常。
- 快速完成的任务:
- 提供了三个示例,演示了
如何使用:
-
引入依赖: 确保你的项目中引入了
slf4j的依赖。 如果使用 Maven:<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.9</version> <!-- 使用最新版本 --> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <!-- 用于控制台输出,生产环境应使用更合适的实现 --> <version>2.0.9</version> <scope>test</scope> </dependency> -
调用方法:
CompletableFuture<String> myFuture = CompletableFuture.supplyAsync(() -> { // 你的耗时操作 return "结果"; }); String result = FutureUtils.getResultWithTimeout(myFuture, 5, TimeUnit.SECONDS); if (result != null) { System.out.println("结果: " + result); } else { System.out.println("获取结果超时或发生错误。"); }
关键改进:
- 恢复中断状态: 捕获
InterruptedException后,通过Thread.currentThread().interrupt()恢复中断状态,这是处理中断的正确做法。 - 更详细的日志: 提供了更详细的日志信息,方便问题排查。
- 单元测试: 提供了单元测试,验证了方法的正确性。
- 代码清晰和可读性: 代码结构清晰,易于理解。
注意事项:
slf4j-simple用于控制台输出,在生产环境中应该使用更合适的slf4j实现,如logback或log4j2。- 根据你的实际业务需求,调整超时时间和日志级别。
- 这个方法返回
null,调用方需要处理null值的情况。 如果你的业务更适合抛出异常,可以修改代码抛出自定义异常。
这个
getResultWithTimeout方法提供了一个安全可靠的方式来从CompletableFuture中获取结果,并在超时或发生错误时进行处理。-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.