网站开发主要框架 后端如何快速推广网上国网

张小明 2026/1/3 4:06:31
网站开发主要框架 后端,如何快速推广网上国网,河北承德网,如何对网站做实证分析往期热门文章#xff1a;1、Spring 项目别再乱注入 Service 了#xff01;用 Lambda 封装个统一调用组件#xff0c;爽到飞起 2、再见Maven#xff01;官方推出全新一代Java项目构建工具#xff0c;性能提升2~10倍 3、程序员的伪年薪百万还能持续多久#xff1f; 4、索引…往期热门文章1、Spring 项目别再乱注入 Service 了用 Lambda 封装个统一调用组件爽到飞起 2、再见Maven官方推出全新一代Java项目构建工具性能提升2~10倍 3、程序员的伪年薪百万还能持续多久 4、索引10连问你能抗住第几问 5、趣图为什么程序员的代码不搞终身责任制?前言CompletableFuture在并发编程中非常实用但如果用不好也很容易踩坑。今天这篇文章跟大家一起聊聊CompletableFuture在使用过程中最常见的那些坑希望对你会有所帮助。一、CompletableFuture简介有些小伙伴在工作中刚开始接触CompletableFuture时可能会被它强大的功能所吸引。确实CompletableFuture为我们提供了非常优雅的异步编程方式但正如武侠小说中的神兵利器如果使用不当反而会伤到自己。CompletableFuture的基本用法先来看一个简单的CompletableFuture使用示例public class BasicCompletableFutureDemo { public static void main(String[] args) throws Exception { // 简单的异步计算 CompletableFutureString future CompletableFuture.supplyAsync(() - { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } returnHello, CompletableFuture!; }); // 获取结果阻塞 String result future.get(); System.out.println(result); } }看起来很简单对吧但正是这种表面上的简单掩盖了很多潜在的复杂性。让我们通过一个架构图来理解CompletableFuture的完整生态现在让我们开始深入探讨各个坑点。二、线程池使用不当有些小伙伴在使用CompletableFuture时往往忽略了线程池的配置这可能是最容易被忽视但影响最大的坑。默认线程池的陷阱public class ThreadPoolPitfall { // 危险的用法大量使用默认线程池 public void processBatchData(ListString dataList) { ListCompletableFutureString futures new ArrayList(); for (String data : dataList) { // 使用默认的ForkJoinPool.commonPool() CompletableFutureString 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 CompletableFutureString processWithProperPool(String data) { return CompletableFuture.supplyAsync(() - { // IO操作使用IO线程池 return fetchFromDatabase(data); }, ioBoundExecutor); } public CompletableFutureString 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() { CompletableFutureString future CompletableFuture.supplyAsync(() - { // 这里会抛出异常 return dangerousOperation(); }); // 添加转换链 CompletableFutureString 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 CompletableFutureString handleWithRecovery() { return CompletableFuture.supplyAsync(() - { return riskyOperation(); }).exceptionally(throwable - { // 异常恢复 System.err.println(操作失败使用默认值: throwable.getMessage()); returndefault-value; }); } // 方法2使用handle统一处理 public CompletableFutureString handleWithUnified() { return CompletableFuture.supplyAsync(() - { return riskyOperation(); }).handle((result, throwable) - { if (throwable ! null) { // 处理异常 System.err.println(操作异常: throwable.getMessage()); returnerror-value; } return result -processed; }); } // 方法3使用whenComplete进行副作用处理 public CompletableFutureVoid handleWithSideEffect() { return CompletableFuture.supplyAsync(() - { return riskyOperation(); }).whenComplete((result, throwable) - { if (throwable ! null) { // 记录日志、发送告警等 logError(throwable); sendAlert(throwable); } else { // 正常业务处理 processResult(result); } }); } // 方法4组合操作中的异常处理 public CompletableFutureString handleInComposition() { CompletableFutureString future1 CompletableFuture.supplyAsync(() - { return operation1(); }); CompletableFutureString future2 future1.thenCompose(result1 - { return CompletableFuture.supplyAsync(() - { return operation2(result1); }); }); // 在整个链的末尾处理异常 return future2.exceptionally(throwable - { Throwable rootCause getRootCause(throwable); if (rootCause instanceof BusinessException) { returnbusiness-fallback; } elseif (rootCause instanceof TimeoutException) { returntimeout-fallback; } else { returnunknown-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 CompletableFutureString 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 CompletableFutureString 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 ListOrder orderHistory; private Discount discount; private Order order; private String result; } public CompletableFutureString 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 CompletableFutureUserProfile getUserProfile(String userId) { CompletableFutureUserInfo userInfoFuture getUserInfo(userId); CompletableFutureListOrder orderHistoryFuture getOrderHistory(userId); CompletableFutureListAddress 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 CompletableFutureMapString, Object getDashboardData(String userId) { CompletableFutureUserInfo userInfoFuture getUserInfo(userId); CompletableFutureListOrder ordersFuture getOrderHistory(userId); CompletableFutureListNotification notificationsFuture getNotifications(userId); CompletableFuturePreferences preferencesFuture getPreferences(userId); CompletableFutureVoid allFutures CompletableFuture.allOf( userInfoFuture, ordersFuture, notificationsFuture, preferencesFuture ); return allFutures.thenApply(v - { MapString, 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 MapString, CompletableFutureString cache new ConcurrentHashMap(); // 场景1无限增长的缓存 public CompletableFutureString 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) { CompletableFutureString future CompletableFuture.supplyAsync(() - { // 模拟长时间运行或阻塞的任务 try { Thread.sleep(Long.MAX_VALUE); // 几乎永久阻塞 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } returnresult; }); // future永远不会完成但一直存在于内存中 } } // 场景3循环引用 publicclass TaskManager { private CompletableFutureString currentTask; private String status INIT; public void startTask() { currentTask CompletableFuture.supplyAsync(() - { // 任务持有Manager的引用 while (!COMPLETED.equals(status)) { // 处理任务 processTask(); } returndone; }); } // Manager也持有任务的引用 public CompletableFutureString getCurrentTask() { return currentTask; } } }内存泄漏检测和预防public class MemoryLeakPrevention { privatefinal CacheString, CompletableFutureString cache; public MemoryLeakPrevention() { // 使用Guava Cache自动清理 this.cache CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterAccess(10, TimeUnit.MINUTES) .removalListener((RemovalListenerString, CompletableFutureString) notification - { if (notification.getCause() RemovalCause.SIZE || notification.getCause() RemovalCause.EXPIRED) { // 取消未完成的任务 CompletableFutureString future notification.getValue(); if (!future.isDone()) { future.cancel(true); } } }) .build(); } // 安全的缓存用法 public CompletableFutureString getDataSafely(String key) { try { return cache.get(key, () - { CompletableFutureString future CompletableFuture.supplyAsync(() - fetchData(key)); // 添加超时控制 return future.orTimeout(30, TimeUnit.SECONDS) .exceptionally(throwable - { // 发生异常时从缓存中移除 cache.invalidate(key); returnfallback-data; }); }); } catch (ExecutionException e) { thrownew RuntimeException(e); } } // 使用WeakReference避免循环引用 publicstaticclass SafeTaskManager { private WeakReferenceCompletableFutureString currentTaskRef; public void startTask() { CompletableFutureString 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() { CompletableFutureString future CompletableFuture.supplyAsync(() - { // 模拟网络问题导致的无限阻塞 return blockingNetworkCall(); }); try { // 如果任务永远不完成这里会永远阻塞 return future.get(); } catch (Exception e) { returnerror; } } // 资源泄漏的示例 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(); } returnresponse; } }完整的超时控制方案public class CompleteTimeoutSolution { privatefinal ScheduledExecutorService timeoutExecutor; public CompleteTimeoutSolution() { this.timeoutExecutor Executors.newScheduledThreadPool(2); } // 方法1使用orTimeoutJava 9 public CompletableFutureString withOrTimeout() { return CompletableFuture.supplyAsync(() - { return externalServiceCall(); }).orTimeout(5, TimeUnit.SECONDS) // 5秒超时 .exceptionally(throwable - { if (throwable instanceof TimeoutException) { returntimeout-fallback; } returnerror-fallback; }); } // 方法2使用completeOnTimeoutJava 9 public CompletableFutureString withCompleteOnTimeout() { return CompletableFuture.supplyAsync(() - { return externalServiceCall(); }).completeOnTimeout(timeout-default, 3, TimeUnit.SECONDS); } // 方法3手动超时控制Java 8兼容 public CompletableFutureString withManualTimeout() { CompletableFutureString taskFuture CompletableFuture.supplyAsync(() - { return externalServiceCall(); }); CompletableFutureString timeoutFuture new CompletableFuture(); // 设置超时 timeoutExecutor.schedule(() - { timeoutFuture.completeExceptionally(new TimeoutException(操作超时)); }, 5, TimeUnit.SECONDS); // 哪个先完成就返回哪个 return taskFuture.applyToEither(timeoutFuture, Function.identity()) .exceptionally(throwable - { if (throwable instanceof TimeoutException) { returnmanual-timeout-fallback; } returnother-error-fallback; }); } // 方法4分层超时控制 public CompletableFutureString 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) { // 根据超时阶段提供不同的降级策略 returntimeout-in-phase; } returngeneral-fallback; }); } // 方法5可配置的超时策略 public CompletableFutureString 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 FunctionThrowable, String fallbackStrategy; } private TimeoutConfig getTimeoutConfig(String operationType) { switch (operationType) { casefast: returnnew TimeoutConfig(1, TimeUnit.SECONDS, t - fast-timeout); casenormal: returnnew TimeoutConfig(5, TimeUnit.SECONDS, t - normal-timeout); caseslow: returnnew TimeoutConfig(30, TimeUnit.SECONDS, t - slow-timeout); default: returnnew TimeoutConfig(10, TimeUnit.SECONDS, t - default-timeout); } } }超时控制策略总结通过上面的详细分析我们可以看到CompletableFuture虽然强大但也确实存在不少陷阱。最后的建议理解原理不要只是机械地使用API要理解CompletableFuture的工作原理适度使用不是所有场景都需要异步同步代码更简单易懂测试覆盖异步代码的测试很重要要覆盖各种边界情况监控告警在生产环境中要有完善的监控和告警机制持续学习关注Java并发编程的新特性和最佳实践记住工具是为了提高生产力而不是制造问题。掌握了这些避坑技巧CompletableFuture将成为你手中强大的并发编程利器往期热门文章1、我有 6 种统计线上接口耗时的方案6种 2、MySQL 模糊查询再也不用like%了 3、从一个程序员的角度告诉你“12306”有多牛逼 4、这才是后端API接口应该有的样子 5、13 秒插入 30 万条数据这才是批量插入的正确姿势 6、面试官MySQL 自增 ID 超过 int 最大值怎么办 7、SpringBoot启动优化7板斧砍掉70%启动时间的魔鬼实践 8、Java25正式发布更简洁、更高效、更现代 9、百万级任务重试框架 Fast-Retry太强了 10、一款牛逼的IDEA插件神器让代码命名变得轻松高效
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

在线房屋建设设计网站龙岩求职信息网

从零构建电影级布料特效:Taichi物理引擎实战指南 【免费下载链接】taichi Productive & portable high-performance programming in Python. 项目地址: https://gitcode.com/GitHub_Trending/ta/taichi 当你在游戏中看到随风飘扬的旗帜,或在动…

张小明 2025/12/31 12:06:25 网站建设

厦门网站建设高级课程wordpress红色

在人工智能技术迅猛发展的今天,多模态AI正成为驱动企业智能化转型的核心引擎。百度最新发布的Qianfan-VL-8B模型,以80亿参数规模构建起面向企业级应用的智能解决方案,通过深度优化工业部署高频场景与保持通用能力的双重突破,重新定…

张小明 2025/12/30 23:35:06 网站建设

长春制作网站中兴通讯的网站建设分析

岗位缺口都达327W了,还犹豫个啥。。。赶紧转行啊。。。。傻子才不转呢! 话是这么说,但天上不会掉馅饼,网络安全为啥这么缺人?内幕可能比你想得更野。笔者在安全圈浸淫5年,亲历过黑产大战、漏洞拍卖&#xf…

张小明 2025/12/23 1:37:14 网站建设

资讯门户类网站有哪些网站建设公司销售技巧

在信息爆炸的时代,如何有效管理个人知识资产成为每个人面临的挑战。传统的云端笔记服务虽然便捷,但往往伴随着数据隐私风险、格式锁定限制。Joplin作为一款开源免费的跨平台笔记应用,重新定义了知识管理的方式,让你真正成为数据的…

张小明 2025/12/23 1:36:12 网站建设

宝安网站制作哪里好wordpress 主题 使用

用 Excalidraw 做产品原型设计,真的比 Figma 更高效吗? 在一次远程需求评审会上,产品经理打开 Figma 链接等了整整两分钟——页面还在加载资源;而隔壁组的工程师只花十秒扔出一个 Excalidraw 链接,所有人立刻进入同一个…

张小明 2025/12/29 7:38:53 网站建设

泸西县住房和城乡建设局网站公司网站开发工具

MIDI编辑器深度体验:浏览器中的专业音乐制作利器 【免费下载链接】midieditor Provides an interface to edit, record, and play Midi data 项目地址: https://gitcode.com/gh_mirrors/mi/midieditor 想要在浏览器中体验专业级的音乐制作吗?MIDI…

张小明 2025/12/23 1:34:09 网站建设