Trong ứng dụng của tôi, tôi phải xử lý nhiều công việc không đồng bộ từ chuỗi ứng dụng chính và thu thập kết quả của từng công việc. Tôi có một giải pháp Java đơn giản thực hiện điều này bằng cách sử dụng ExecutorService và ExecutorCompletionService để thu thập kết quả công việc.Tương đương với mùa xuân của CompletionService?
Bây giờ tôi muốn chuyển đổi mã của mình thành giải pháp Mùa xuân. docs chỉ cho tôi cách sử dụng chú thích ExecutorService và @Async, nhưng tôi không chắc chắn cách thức và nếu tôi có thể thu thập kết quả của nhiều công việc.
Nói cách khác: Tôi đang tìm kiếm tương đương Spring của CompletionService. Có một điều như vậy?
mã hiện tại của tôi:
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));
}
}