Home > OS >  Spring Boot @Async await That all thread completed
Spring Boot @Async await That all thread completed

Time:10-14

I have to do several connection to different servers and run some commands, I'm using a for to call an Async method but I don't know when all threads completed to send other process.

CodePudding user response:

You can wrap the result of the @Async method using CompletableFuture. Return it such that you can make use of the feature provided by the CompletableFuture to achieve your purpose.

For example :

@Service
public class FooService {
   
   @Async
   public CompletableFuture<String> process(){
       String result = processing();
       return CompletableFuture.completedFuture(result);
   }

}

And the client codes :

CompletableFuture<String> r1 =   fooService.process();
CompletableFuture<String> r2 =   fooService.process();
CompletableFuture<String> r3 =   fooService.process();
  
CompletableFuture.allOf(r1,r2,r3).join(); 

System.out.println("All threads are completed now");

CodePudding user response:

thanks, I used another solution, I used a collection and Used a for loop to review that, for example:

@Async
public Future<Void> executeBla() {
    System.out.println("Bla!");
    return new AsyncResult<Void>(null);
}
public void executeBlaALotOfTimes() {
    long before = System.currentTimeMillis();

    Collection<Future<Void>> futures = new ArrayList<Future<Void>>();

    for (int i = 0; i<40000; i  ) {
        futures.add(executeBla());
    }

    for (Future<Void> future : futures) {
        future.get();
    }

    long after = System.currentTimeMillis(); 

    System.out.println("Time it took for a lot of bla to execute: "   (after - before) / 1000.0   " seconds.");
}

I view this option in @Async prevent a thread to continue until other thread have finished

  • Related