开发者

Java EJB @Asynchronous loop - How to know when all the calls are complete before moving on?

I have this code in an ejb

for (PayrollEntry pe : payroll.getEntries()) {
    recalculateP开发者_运维技巧ayrollEntry(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?


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜