【发布时间】:2019-05-22 23:39:18
【问题描述】:
我正在编写一个代码,它从文件中挑选多个 API 调用详细信息并逐个执行这些详细信息,并在 ArrayList 中提供响应数据。以下是我当前的代码。
ArrayList<APICallDetails> apiCallDetailsArray = new ArrayList<>();
APICallDetails apiCallDetails = new APICallDetails();
for (count= 1; count <= callsCount; count++){
try{
apiCallDetails = new APICallDetails();
apiCallDetails.setName(property.getPropertyReader(callName+"_"+count+"_Name", propsFile));
apiCallDetails.setHost(marketConfigs.getRawJson().get(property.getPropertyReader(callName+"_"+count+"_Host", propsFile)).toString().replaceAll("\"", ""));
apiCallDetails.setPath(property.getPropertyReader(callName+"_"+count+"_Path", propsFile));
apiCallDetails.setMethod(property.getPropertyReader(callName+"_"+count+"_Method", propsFile));
apiCallDetails.setBody(property.getPropertyReader(callName+"_"+count+"_Body", propsFile));
apiCallDetails = sendAPIRequest.mwRequestWithoutBody(apiCallDetails, marketConfigs);
BufferedWriter out = null;
try {
out = new BufferedWriter ( new FileWriter ( "C:\\file"+count+".html"));
out.write("something");
out.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(new Date()+" - Error in "+getClass()+".apiCallRequester() flow: "+e.toString());
}
apiCallDetailsArray.add(apiCallDetails);
}catch(NullPointerException e){
e.printStackTrace();
logger.error(new Date()+" - Error in "+getClass()+".apiCallRequester() flow: "+e.toString());
}
}
由于有更多的 API 调用,这是所有调用的响应时间的总和。我希望这些调用并行运行并将响应数据存储在一个 ArrayList 中,我可以进一步使用它。 我是Java新手,有人可以帮我吗?
【问题讨论】:
-
查看 CompletableFuture。
-
这个for循环也有点过时了。查看 Streams API 以获得更具表现力的迭代构造。 (奖金,流是微不足道的并行化)。请注意,Java 对象并非都是固有的线程安全的,
sendAPIRequest可能不喜欢被并行调用。
标签: java multithreading algorithm design-patterns java-8