Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting Return Values from Launched Threads? [latest Java]

I'm looking for the simplest, most straightforward way to implement the following:

  • main starts and launches 3 threads
  • all 3 tasks process and end in a resulting value (which I need to return somehow?)
  • main waits (.join?) on each thread to ensure they have all 3 completed their task
  • main somehow gets the value from each thread (3 values)

Then the rest is fairly simple, processes the 3 results and then terminates...

Now, I've been doing some reading and found multiple ideas, like:

  • Using Future, but this is for asynch, is this really a good idea when the main thread needs to block waiting for all 3 spawned threads to finsih?
  • Passing in an object (to a thread) and then simply having the thread "fill it" with the result
  • Somehow using Runnable (not sure how yet).

Anyways - what would be the best, and simplest recommended approach? Thanks,

like image 286
Shaitan00 Avatar asked Sep 13 '26 05:09

Shaitan00


1 Answers

List<Callable<Result>> list = ... create list of callables

ExecutorService es = Executors.newFixedThreadPool(3);
List<Future<Result>> results = es.invokeAll(list);

ExecutorService.invokeAll method will return only after all tasks (instances of Callable) finished, either normally or by throwing exception.

For details see ExecutorService (mainly its invokeAll method), Executors, Callable.

like image 140
Peter Štibraný Avatar answered Sep 16 '26 21:09

Peter Štibraný