Java EJB @Asynchronous循环 - 在继续之前如何知道所有调用何时完成?

发布于 2024-12-02 13:16:29 字数 390 浏览 2 评论 0 原文

ejb 中有此代码

for (PayrollEntry pe : payroll.getEntries()) {
    recalculatePayrollEntry(pe);
}

CalculateTotals(payroll);

我在调用此异步方法的

@Asynchronous
public void recalculatePayrollEntry(PayrollEntry pe) {
    // Calculate Payroll Entry;
    pe.setEarningsEntries(newEarnings);
}

在调用 CalcuateTotals 之前等待所有这些重新计算执行的最佳方法是什么?

I have this code in an ejb

for (PayrollEntry pe : payroll.getEntries()) {
    recalculatePayrollEntry(pe);
}

CalculateTotals(payroll);

which calls this async method

@Asynchronous
public void recalculatePayrollEntry(PayrollEntry pe) {
    // Calculate Payroll Entry;
    pe.setEarningsEntries(newEarnings);
}

What is the best way to wait until all those recalculations execute before calling CalcuateTotals?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半仙 2024-12-09 13:16:29

不要将异步方法设置为 void,而是返回 Future(代表异步计算)。启动作业,收集所有 future,然后等待它们完成:

Future<?> recalculatePayrollEntry(PayrollEntry pe) {
    // Calculate Payroll Entry;
    pe.setEarningsEntries(newEarnings);
    return new AsyncResult<Object>(null); // just something symbolic
}

// Usage:
List<Future<?>> results = new ArrayList<>();
for (PayrollEntry pe : payroll.getEntries()) {
    results.add(recalculatePayrollEntry(pe));
}
for (Future<?> result : results){
    result.get(); // await completion
}

CalculateTotals(payroll);

Instead of having your async method as void, return a Future (which represent an asynchronous calculation). Start up the jobs, collect all the futures, and then await their completion:

Future<?> recalculatePayrollEntry(PayrollEntry pe) {
    // Calculate Payroll Entry;
    pe.setEarningsEntries(newEarnings);
    return new AsyncResult<Object>(null); // just something symbolic
}

// Usage:
List<Future<?>> results = new ArrayList<>();
for (PayrollEntry pe : payroll.getEntries()) {
    results.add(recalculatePayrollEntry(pe));
}
for (Future<?> result : results){
    result.get(); // await completion
}

CalculateTotals(payroll);
计㈡愣 2024-12-09 13:16:29

我相信您可以让您的方法返回 AsyncResult 是一个 Future。该方法的返回类型应为 Future

收集列表中的所有 future,然后对每个调用 .get()

I believe you can have your method return an AsyncResult which is a Future. The return type of the method should be Future

Collect all futures in a list, and then call .get() on each.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文