简体   繁体   English

锁定Java EE应用程序

[英]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: 到目前为止我的方法:

  1. 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. 在这种方法中,我喜欢并发访问将被阻止,我可以控制其他线程尝试锁定资源的时间。

  2. Use JPA2 optimistic locking. 使用JPA2乐观锁定。

Which one would you recommend? 你会推荐哪一个? Or is there an even better approach? 还是有更好的方法?

  1. seems error-prone, plus it might not scale. 似乎容易出错,加上它可能无法扩展。 I've never seen such design and would discourage it. 我从来没有见过这样的设计,会劝阻它。
  2. transactions with optimistic locking is a viable option. 具有乐观锁定的交易是可行的选择。 In this case, some transaction might fail and you will need to deal with errors and retry. 在这种情况下,某些事务可能会失败,您将需要处理错误并重试。
  3. transactions with pessimistic locking is another viable option. 具有悲观锁定的交易是另一种可行的选择。 It's like 1) but using the database to lock and order operations. 这就像1)但使用数据库来锁定和订购操作。 AFAIK, JPA support pessimistic locking as well. AFAIK,JPA也支持悲观锁定。 Otherwise you can use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM