简体   繁体   中英

Java - Threading HttpUrlConnection calls

I have a custom service module where I pass up a JSON body, containing an array of IDs. I have to iterate through these IDs and make a separate web service call with each ID to obtain a response body, then aggregate these responses into a custom JSON structure. I have that all working, but I'd like to implement threading (or some manner thereof) to make the HTTP calls asynchronously, rather than in succession. How would I implement threading in the following code:

    ids = (JSONArray) jsonIn.get("IDs");    

    MyClass myClass = null;
    List<MyClass> myClassList = new ArrayList<MyClass>();

    for (int i = 0; i < ids.size(); i++) {
        JSONObject p = (JSONObject)ids.get(i);
        id = p.get("ID").toString();

        //The HttpUrlConnection call is made in the getResponse() method
        Gson gson = new Gson();
        MyClassResponse result = gson.fromJson(getResponse(),
                MyClassResponse.class);

        for (int x = 0; x < result.ids[0].id.length; x++) {

            myClass = new MyClass();

            myClass.setStringOne(result.ids[0].fieldOne);
            myClass.setStringTwo(result.ids[0].fieldTwo);

            myClassList.add(x, myClass);
        }           
    }

    Gson gsonOut = new Gson();
    String jsonString = gsonOut.toJson(myClassList);

    JsonArray jsonArray = new JsonParser().parse(jsonString).getAsJsonArray();

    JSONObject response = new JSONObject();
    response.put("CustomStructure", jsonArray);

    //pass back custom JSON body

Use this logic:

  • Create a Runnable that does what your loop is doing, constructor taking the individual JSONObject as input.
  • Store the output MyClassResponse as a member variable in your runnable.
  • Have a list of threads and List of Runnable declared outside the loop
  • Create the thread and runnable inside the loop and add it to the lists
  • start the thread inside the loop
  • After the loop call Thread.join on each of the threads in the list of threads (This makes this thread wait till the threads are completed.)
  • create your MyClassList from the list of runnables once all the join statements have returned back

This is how I implemented it:

/***Code to execute threads***/
Thread[] threads = new Thread[ids.size()];

for (int i = 0; i < ids.size(); i++) {
    JSONObject p = (JSONObject)id.get(i);
    id = p.get("ID").toString();

    threads[i] = new Thread(new DoThread(id));
    threads[i].start();
}

for(int i = 0; i < id.size(); i++) {
    threads[i].join();
}
/*****************************/

public class DoThread implements Runnable {

    private String id;
    public DoThread(String id) {
        this.id = id;
    }

    public void run() {

        //Do Work   

    }
}

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