RubberPoach
RubberPoach

Reputation: 5

Which locking mechanism to use in JavaEE application with Oracle DB?

i'm trying to create a multiuser JavaEE application with JPA and Oracle DB. In my previous apps I used the ReentrantReadWriteLock Java class for locking the data ressources. Now I saw that JPA provides support for optimistic and pessimistic locking and Oracle locks ressources automatically depending on the isolation level.
So I wonder which is the best way to do the locking? In java with ReentrantReadWriteLock, using JPA or directly in the database? Do I even need to implement additional locking in java or can I simply rely on the automatic locking mechanisms of Oracle?
Thanks for your answers.

Upvotes: 0

Views: 258

Answers (2)

ibre5041
ibre5041

Reputation: 5288

For Oracle pessimistic locking is natural choice. Since it has no performance trade-offs - simply because it is used anyway and there is no way how to turn it off. But this implies that your ORM framework MUST serialize queries it the right order - otherwise they will get deadlocked. You will receive ORA-00060 error. From Oracle's point of view deadlock is always caused by wrong application design. Unfortunately ORMs do not give you control on the SQL statements ordering and deadlock issues are very hard to fix for Java developers. Also Oracle specific errors are "unreachable" for Java developers.

On then contrary with optimistic locking ORM/JPA framework will throw "OptimisticLockingException", the application will clear the form and will let user to enter the values again and then you can retry to store data in the DB.

Upvotes: 0

Chris
Chris

Reputation: 21145

It depends on what your application needs. Any sort of locking has performance tradeoffs - you trade throughput for accuracy. But you also have to look at future use. Java locks are great, as long as you never plan to access the same data outside the current JVM. Its not something I would look at unless you need to lock resources that exist within the JVM/server environment from being used concurrently. Otherwise I would look at database locking mechanisms, as this allows more flexibility and expansion later on, such as if another app starts using the same database. So you may still want a database lock mechanism even if you use java locks.

Pessimistic locking and its variations give your app the ability to control reading stale data, but is over kill for most applications IMO. It is used if your application's users consistently modify the same common data over and over, such that it makes sense to force them to wait until another user is done. More common is optimistic locking, which allows users to read data unrestricted, but will prevent overwriting data with stale data.

See http://en.wikibooks.org/wiki/Java_Persistence/Locking

Upvotes: 1

Related Questions