我尝试让异步进程运行。基于这个例子:http ://tomee.apache.org/examples-trunk/async-methods/README.html
但是只有当代码完全完成时,该方法addWorkflow(Workflow workflow)
才会返回。run(Workflow workflow)
然后当它返回并被result.get();
调用时,我会得到异常:
原因:java.lang.IllegalStateException:对象不代表实际的未来
任何建议我错过了什么?
@Singleton
public class WorkflowProcessor {
@EJB
private WorkflowManager workflowManager;
private final static Logger log = Logger.getLogger(WorkflowProcessor.class.getName());
public void runWorkflows(Collection<Workflow> workflows) throws Exception{
final long start = System.nanoTime();
final long numberOfWorkflows = workflows.size();
Collection<Future<Workflow>> asyncWorkflows = new ArrayList<>();
for(Workflow workflow : workflows){
Future<Workflow> w = addWorkflow(workflow);
asyncWorkflows.add(w);
}
log.log(Level.INFO, "workflow jobs added {0}", new Object[]{numberOfWorkflows});
for(Future<Workflow> result : asyncWorkflows){
result.get();
}
final long total = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
log.log(Level.INFO, "WorkflowProcessor->runWorkflows {0} workflows completed in:{1}", new Object[]{numberOfWorkflows, total});
}
@Asynchronous
@Lock(LockType.READ)
@AccessTimeout(-1)
private Future<Workflow> addWorkflow(Workflow workflow){
run(workflow);
return new AsyncResult<Workflow>(workflow);
}
private void run(Workflow workflow){
this.workflowManager.runWorkflow(workflow);
}