Java - Wait for Lambda to Finish before continuing

1531 views java
-3

I have to get data from an API, so naturally I have an endpoint handeler that is accessed through a lambda that, I assume, spawns off several threads to complete each API call that I need. However, After all of the API calls are finished (all of the lambda threads complete) I need to oranize my data. Currently, the Sort method that I have runs on the main thread, and therefore finishes before any of the API calls in the lambda finish. Here is a sample of what I have

for(String data : dataArray) {
    APIEndpoint apiCall = new APIEndpoint("http://sampleAPI.org/route/" + data);
    apiCall.execute(((response, success) -> {
        //Format and gather the info from the response
        apiDataArray.add(DataFromAPIObject);
    }));
}
System.out.print(apiDataArray.size());//Returns 0
sortData();//Currently Doesn't Sort anything because the array is empty

answered question

Why don't you move the sortData() call into the lambda/callback ?

Does the APIEndpoint.execute method return anything, like a Future? If it doesn’t, you can always use apiDataArray.add(index, DataFromAPIObject), where index is determined using Collections.binarySearch.

You need to create Futures in the call and wait for their completion outside the loop before sorting.

Use a callback interface or semaphore

1 Answer

3

Using semaphores might be an option. But it will deadlock if for some reason there is no response for at least one of the data points. (To fix the deadlock you might need to release the semaphore on errors).

    Semaphore semaphore = new Semaphore(dataArray.length);
    for (String data : dataArray) {         
        APIEndpoint apiCall = new APIEndpoint("http://sampleAPI.org/route/" + data);
        apiCall.execute(((response, success) -> {
            // Format and gather the info from the response
            apiDataArray.add(DataFromAPIObject);
            semaphore.release();
        }));
    }
    semaphore.acquire(dataArray.length);
    sortData();

posted this

Have an answer?

JD

Please login first before posting an answer.