I have below method in my application and it's looks working fine.. but i m not sure how it is...
ArrayList arr = new ArrayList();
Collection<Future<?>> futures = new LinkedList<Future<?>>();
RestCallThread thread = null;
HttpHeaders header = getAuthHeader(authorization);
for (String ids : IDS) {
thread = new RestCallThread(ids, header);
futures.add(executor.submit(thread));
}
for (Future<?> future : futures) {
try {
arr.add(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
return arr;
In the code RestAPI calls are added to the ThreadPoolExecutor and waiting for the result..
My Question is Since the approach is based on thread how the return statement is not executed till all the API threads get completed...
Any chance of return statement will return empty list?
My Question is Since the approach is based on thread how the return statement is not executed till all the API threads get completed...
Read the JavaDoc on Future#get()
:
Waits if necessary for the computation to complete, and then retrieves its result.
That means the loop is blocked until the current iteration's future get its result, i.e. when the loop is finished you know that all threads have finished.
Any chance of return statement will return empty list?
Yes, e.g. if IDS
is empty or if all the threads fail with an exception.