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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With