【发布时间】:2012-02-14 13:53:20
【问题描述】:
我们有一个 HTTP 端点,它需要很长时间才能运行,也可以由用户并发调用。作为此请求的一部分,我们在同步块内更新模型,以便其他(可能并发的)请求获取该更改。
例如
MyModel m = null;
synchronized (lockObject) {
m = MyModel.findById(id);
if (m.status == PENDING) {
m.status = ACTIVE;
} else {
//render a response back to user that the operation is not allowed
}
m.save(); //Is not expected to be called unless we set m.status = ACTIVE
}
//Long running operation continues here. It can involve further changes to instance "m"
synchronized 块的原因是为了确保即使是并发请求也能获取最新状态。但是,在请求完成之前,底层 JPA 不会提交我的更改 (m.save())。由于这是一个长时间运行的请求,我不想等到请求完成后仍想确保通知其他调用者状态更改。我试图调用“m.em().flush(); JPA.em().getTransaction().commit();”在 m.save() 之后,但这使得事务对于作为同一请求的一部分的后续操作不可用。我可以只给出“JPA.em().getTransaction().begin();”吗然后让 Play 处理交易?如果不是,那么处理这个用例的最佳方法是什么?
更新: 根据回复,我修改了我的代码如下:
MyModel m = null;
synchronized (lockObject) {
m = MyModel.findById(id);
if (m.status == PENDING) {
m.status = ACTIVE;
} else {
//render a response back to user that the operation is not allowed
}
m.save(); //Is not expected to be called unless we set m.status = ACTIVE
}
new MyModelUpdateJob(m.id).now();
在我的工作中,我有以下几行:
doJob() {
MyModel m = MyModel.findById(id);
print m.status; //This still prints the old status as-if m.save() had no effect...
}
我错过了什么?
【问题讨论】:
标签: jpa playframework