Java并发编程:使用CompletableFuture高效有序处理批量接口请求
高并发访问第三方接口能显著提升数据处理效率,但如果不控制线程执行顺序,最终结果可能与原始数据顺序不符,导致后续处理错误。本文介绍如何利用Java的CompletableFuture在多线程环境下,确保接口请求及结果处理的有序性。
问题:直接使用CompletableFuture.runAsync
进行异步调用,由于线程执行顺序不可预测,导致返回结果与原始数据列表顺序不一致。CompletableFuture.allOf
仅能保证所有任务完成,无法保证顺序。
解决方案:使用CompletableFuture.supplyAsync
,它能返回结果。将每个异步任务的返回结果存储在CompletableFuture<string></string>
列表中,所有任务完成后,通过stream().map(CompletableFuture::join).collect(Collectors.toList())
按原始顺序收集结果。
改进后的代码示例:
public static void main(String[] args) { List<string> dataList = new ArrayList(); // 原始数据列表 // ... 初始化dataList ... ExecutorService executorService = new ThreadPoolExecutor( 10, // corePoolSize 20, // maximumPoolSize 60L, // keepAliveTime TimeUnit.SECONDS, new LinkedBlockingQueue(1024), // workQueue new ThreadPoolExecutor.CallerRunsPolicy() // handler ); List<completablefuture>> futures = new ArrayList(); for (String data : dataList) { futures.add(CompletableFuture.supplyAsync(() -> { logger.info("Processing data: {}", data); // 调用第三方接口,处理data // ... 接口调用及结果处理逻辑 ... return data " - Processed Result"; // 返回处理结果 }, executorService)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRun(() -> { List<string> results = futures.stream() .map(CompletableFuture::join) .collect(Collectors.toList()); logger.info("All tasks completed. Results: {}", JSON.toJSONString(results)); // 后续处理结果 }).thenRun(() -> executorService.shutdown()); }</string></completablefuture></string>
改进后的代码使用CompletableFuture.supplyAsync
返回每个接口调用的结果,并存储在futures
列表中。CompletableFuture.allOf
确保所有任务完成后再处理结果,stream().map(CompletableFuture::join).collect(Collectors.toList())
保证结果按原始顺序收集,从而解决了并发导致结果顺序错乱的问题。 代码还使用了自定义线程池,以便更好地控制资源使用。
以上是如何利用CompletableFuture保證批量接口請求的順序並高效處理結果?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Java在不同操作系統上的表現存在細微差異。 1)JVM實現不同,如HotSpot、OpenJDK,影響性能和垃圾回收。 2)文件系統結構和路徑分隔符不同,需使用Java標準庫處理。 3)網絡協議實現差異影響網絡性能。 4)GUI組件外觀和行為在不同系統上有別。通過使用標準庫和虛擬機測試,可減少這些差異的影響,確保Java程序穩定運行。

javaoffersrobustobject-IentiendedProgrammming(OOP)和Top-Notchsecurityfeatures.1)OopinjavainCludesClasses,對象,繼承,多態性,和列出,andeclingfleximaintainablesys.ss.2)SecurityFeateTuersLudEtersludEterMachine(

JavaScriptandJavahavedistinctstrengths:JavaScriptexcelsindynamictypingandasynchronousprogramming,whileJavaisrobustwithstrongOOPandtyping.1)JavaScript'sdynamicnatureallowsforrapiddevelopmentandprototyping,withasync/awaitfornon-blockingI/O.2)Java'sOOPf

JAVAACHIEVESPLATFORMINDEPENTENCETHROUGHJAVAVIRTAILMACHINE(JVM)和BYTECODE.1)THEJVMINTERPRETSBBYTECODE,允許theingthesmecodetorunonanyanyanyanyplatformwithajvm.2)

java'splatformendependecemeansapplicationscanrunonanyplatformwithajvm,使“ Writeonce,runanywhere”。

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版
中文版,非常好用

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。