Issue
I want execute some java logic with multiple threads and that method return a List. So finally I want all threads result into single List? Is it possible with Java ExecutorService or Multithreading ? or any other java frameworks ?
Solution
There are different ways to do it, here is my suggestion:
Create a list of Callable
(see more about it in the docs):
List<Callable<Object>> callables = new ArrayList<>();
Add your tasks to this list:
callables.add(() -> {
// do something
});
Then invoke those Callables by passing them to the invokeAll()
method of ExecutorService
and receive a List of Future<Object>
. For example:
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<Object>> results = executor.invokeAll(callables);
You can then get each of the thread results by getting them via index call from the result
list - in the same order as which you passed them to your Callable list.
So, to get the result of the first thread that you passed to the Callable list, simply do:
CastedResult result = (CastedResult) results.get(0).get();
Finally, you can collect all results in a single list as you wish.
Also, this is a helpful article on how to use ExecutorService
(and remember to shutdown the Executor after you finish working with it, as explained here).
Answered By - Petar Bivolarski