简体   繁体   中英

Locking in Java EE Application

I am using Java EE 6 with JBOSS7 and JPA2 + Hibernate. For my client I provide a 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. (my ids are always UUID s) Locks are created on demand if missing in map. 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.

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. AFAIK, JPA support pessimistic locking as well. Otherwise you can use SELECT FOR UPDATE (supported by most DBMS) to explicitely acquire row locks. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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