在我的应用程序中,我必须从主应用程序线程异步处理多个作业并收集每个作业的结果。我有一个简单的 Java 解决方案,它使用 ExecutorService 和 ExecutorCompletionService 来收集作业结果。
现在我想将我的代码转换为 Spring 解决方案。文档向我展示了如何使用 ExecutorService 和 @Async 注释,但我不确定如何以及是否可以收集多个作业的结果。
换句话说:我正在寻找与 CompletionService 等效的 Spring。有这样的事吗?
我当前的代码:
class MyService {
private static ExecutorService executorService;
private static CompletionService<String> taskCompletionService;
// static init block
static {
executorService = Executors.newFixedThreadPool(4);
taskCompletionService = new ExecutorCompletionService<String>(executorService);
// Create thread that keeps looking for results
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Future<String> future = taskCompletionService.take();
String s = future.get();
LOG.debug(s);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}).start();
}
// This method can and will be called multiple times,
// so multiple jobs are submitted to the completion service
public void solve(List<Long> ids) throws IOException, SolverException {
String data = createSolverData(ids);
taskCompletionService.submit(new SolverRunner(data, properties));
}
}