Код: Выделить всё
private void init() throws ExecutionException, InterruptedException {
Long start = System.currentTimeMillis();
List responses = fetchAllUsingFuture(ids, 3);
log.info(responses.toString());
Long finish = System.currentTimeMillis();
log.info(MessageFormat.format("Process duration: {0} in ms", finish-start));
}
private List fetchAllUsingFuture(List ids, int threadCount) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
List chunks = Utils.splitToChunks(ids, threadCount);
List futures = new ArrayList();
chunks.forEach(chunk -> {
futures.add(wrapFetchInFuture(chunk));
});
Future resultFuture = executorService.submit(() -> {
List responses = new ArrayList();
futures.forEach(future -> {
try {
responses.addAll(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
return responses;
});
executorService.shutdown();
return resultFuture.get();
}
private Future wrapFetchInFuture(List ids) {
return new FutureTask(() -> {
List responses = new ArrayList();
ids.forEach(id -> {
responses.add(fetchData(id));
});
return responses;
});
}
private ApiResponse fetchData(String id) {
ResponseEntity response = restTemplate.getForEntity(id, ApiResponse.class);
log.info(MessageFormat.format("Fetching from {0}", id));
ApiResponse body = response.getBody();
log.info(MessageFormat.format("Retrieved {0}", body));
return body;
}
P.S. Я знаю, что это гораздо проще сделать с помощью CompletableFuture, мне просто интересно, как это сделать с помощью Futures
Подробнее здесь: https://stackoverflow.com/questions/632 ... es-in-java