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

bharat dangi :

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?

Marco R. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88593&siteId=1