You can use the Executors.newFixedThreadPool(int)
method to get an ExecutorService to submit tasks to.
Each task that you submit to the thread pool will return a Future
, which you can maintain a list of and retrieve the returned value at a later time.
Here's an example:
// Create a new fixed thread pool with a predefined number of threads.final ExecutorService service = Executors.newFixedThreadPool(10);// Create a list of Future objects to retrieve later.List<Future<Map<String, Object>>> futures = new ArrayList<>();// Loop through your list and for each iteration, submit your task// to the Executor service, and add the result to your Future list.for (Map<String, Object> fund: fundsList) { futures.add(service.submit(() -> doCalc(/* parameters */)));}// Loop through the Future list and call the .get() method to// retrieve the computed value.for (Future<Map<String, Object>> future: futures) { try { final Map<String, Object> finalData = future.get(); expectedDataList.add(finalData); } catch (InterruptedException | ExecutionException e) { // log or throw error }}