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:
-
Map<String, ReentrantLock>to store the locks. (my ids are always
UUIDs) 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. -
Use JPA2 optimistic locking.
Which one would you recommend? Or is there an even better approach?
design and would discourage it.
locking is a viable option. In this case, some transaction might
fail and you will need to deal with errors and retry.
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 youfigure out a scheme were locks are acquired in consistent order, to
avoid deadlocks.
The choice between 2-3 depends on the use case, e.g. if contention is expected to be high or not, or whether it is easy to retry a failed transaction.