Java 如何检查在 Spring 中完成的 @Async 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29181057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check that @Async call completed in Spring?
提问by DnA
Im using @Asyncannotation for method that execute rsync command. There are ten threadscalling 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
我对执行 rsync 命令的方法使用@Async注释。一次有十个线程调用此方法。我的要求是在所有十个线程完成 rsync 命令执行之后,只有我剩余的代码应该执行,但没有得到如何检查我的所有十个线程是否完全执行了 @Async 方法?所以请告诉我一种检查方法
采纳答案by luboskrnac
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.
如果您要返回一些值,您应该将返回值包装到标准 Java SEFuture
或 Spring 的 中AsyncResult
,它们Future
也实现了。
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.
CallfutureResult.get()
将阻塞调用者线程并等待异步线程完成。
Optionally you can use Future.get(long timeout, TimeUnit unit)
if you don't want to wait forever.
Future.get(long timeout, TimeUnit unit)
如果您不想永远等待,您可以选择使用。
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
}