dimilalabar
dimilalabar

Reputation: 85

Execute multiple java methods asynchronously and get the results on job done

how to execute multiple java methods asynchronously and get the results on job done for each method? Lets say I have this:

for(int i=1; i<=10000; i++) {
    kur(i);
}

//on kur(i) finish -> System.out.println(kur(i)) or System.out.println(Exception e)


Info kur(int i) throws Exception {
   //do some stuff
   return new Info(...);
}

I can use spring boot also. I checked this: https://spring.io/guides/gs/async-method/ but it is different than my case.

Could you help me?

Upvotes: 0

Views: 172

Answers (1)

Not a JD
Not a JD

Reputation: 1902

(ORIGINAL ANSWER) Maybe an ExecutorService could help you?

ExecutorService executorService = Executors.newFixedThreadPool(10);

IntStream.rangeClosed(1, 10000)
         .forEach(i -> {
             executorService.submit(() -> {
                 try {
                     System.out.println(kur(i));
                 } catch (Exception e) {
                     // do something useful here - remember you're in a separate thread
                     //
                     // this is not useful.
                     e.printStackTrace();
                 }
             });
         });

executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);

(EDIT WITH POOR MAN'S SOLUTION TO WAIT FOR EVERYTHING TO COMPLETE):

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    List<Future<?>> futures = IntStream.rangeClosed(1, 10000)
                                       .mapToObj(i -> {
                                           return executorService.submit(() -> {
                                               try {
                                                   System.out.println(kur(i));
                                               } catch (Exception e) {
                                                   // do something useful here - remember you're in a separate thread
                                                   //
                                                   // this is not useful.
                                                   e.printStackTrace();
                                               }
                                           });
                                       })
                                       .collect(Collectors.toList());

    for (Future<?> f : futures) {
        f.get();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

Upvotes: 2

Related Questions