How to check that @Async call completed in Spring?

后端 未结 1 536
星月不相逢
星月不相逢 2020-12-29 09:28

Im using @Async annotation for method that execute rsync command. There are ten threads calling this method at a time. My requirement is af

相关标签:
1条回答
  • 2020-12-29 10:24

    If you are going to return some value, you should wrap your return value into Standard Java SE Future or Spring's AsyncResult, which implements Future also.

    Something like this:

    @Component
    class AsyncTask {
      @Async
      public Future<String> call() throws InterruptedException {
        return new AsyncResult<String>("return value");
      }
    }
    

    If you do have this in place, in caller you do something like:

    public void kickOffAsyncTask() throws InterruptedException {
      Future<String> futureResult =  asyncTask.call();
    
      //do some stuff in parallel
    
      String result = futureResult.get();
      System.out.println(result);
    }
    

    Call futureResult.get() will block caller thread and wait until your async thread finishes.

    Optionally you can use Future.get(long timeout, TimeUnit unit) if you don't want to wait forever.

    EDIT:

    If you don't need to return any value, I would still suggest to consider returning dummy return value. You don't need to use it for anything, just use to indicate that particular thread completed. Something like this:

    public void kickOffAsyncTasks(int execCount) throws InterruptedException {
      Collection<Future<String>> results = new ArrayList<>(execCount);
    
      //kick off all threads
      for (int idx = 0; idx < execCount; idx++) {
        results.add(asyncTask.call());
      }
    
      // wait for all threads
      results.forEach(result -> {
        try {
          result.get();
        } catch (InterruptedException | ExecutionException e) {
          //handle thread error
        }
      });
    
      //all threads finished
    }
    
    0 讨论(0)
提交回复
热议问题