Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that @Async call completed in Spring?

Im using @Async annotation for method that execute rsync command. There are ten threads calling this method at a time. My requirement is after all ten threads complete rsync command execution then only my remaining code should execute but not getting how to check whether my all ten threads has executed @Async method completely or not? So please tell me a way to check it

like image 672
DnA Avatar asked Mar 21 '15 09:03

DnA


1 Answers

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
}
like image 126
luboskrnac Avatar answered Oct 08 '22 12:10

luboskrnac