[英]Locking in Java EE Application
I am using Java EE 6 with JBOSS7 and JPA2 + Hibernate. 我正在使用Java EE 6和JBOSS7以及JPA2 + Hibernate。 For my client I provide a REST api. 对于我的客户,我提供了一个REST API。
My concern is how to efficiently ensure that no resources where modified concurrently. 我关心的是如何有效地确保没有资源同时被修改。 Should happen too often, but in case it happens I would like to ensure proper handling. 应该经常发生,但如果发生这种情况,我想确保正确处理。
My approaches so far: 到目前为止我的方法:
Map<String, ReentrantLock>
to store the locks. Map<String, ReentrantLock>
以存储锁。 (my ids are always UUID
s) Locks are created on demand if missing in map. (我的ID总是UUID
)如果在地图中丢失,则按需创建锁。 On this approach i like that concurrent access will be blocked and i can control how long the other thread tries to lock the resource. 在这种方法中,我喜欢并发访问将被阻止,我可以控制其他线程尝试锁定资源的时间。
Use JPA2 optimistic locking. 使用JPA2乐观锁定。
Which one would you recommend? 你会推荐哪一个? Or is there an even better approach? 还是有更好的方法?
SELECT FOR UPDATE
(supported by most DBMS) to explicitely acquire row locks. 否则,您可以使用SELECT FOR UPDATE
(大多数DBMS支持)明确获取行锁。 Make sure you figure out a scheme were locks are acquired in consistent order, to avoid deadlocks. 确保你弄清楚一个方案是以一致的顺序获取锁,以避免死锁。 The choice between 2-3 depends on the use case, eg if contention is expected to be high or not, or whether it is easy to retry a failed transaction. 2-3之间的选择取决于用例,例如,如果争用预期很高或者是否很容易重试失败的事务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.