简体   繁体   中英

How to use multi-threading to parallellize a for loop in Java?

I am writing a code which picks the multiple API call details from a file and executes those ones by one and provides the response data in an ArrayList. Below is my current code.

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());
        }
    }

As there are more API calls, this is taking the sum of the response time of all the calls. I want these calls to run parallelly and store the response data in an ArrayList which I can use further. I am new to Java so, can someone please help me with this?

You can use parallel streams. The following invocation will invoke in parallel createAPICallDetails(idx) and add their return objects into a List :

    List<APICallDetails> result = IntStream.range(0, callsCount)
            .parallel()
            .mapToObj(idx -> createAPICallDetails(idx))
            .collect(Collectors.toList());

So, the only thing left for you is to implement the logic of:

    APICallDetails createAPICallDetails(int index) { ... }

To create a single object of your APICallDetails given the index argument, so it can be used in the previous lambda.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM