Brijesh
Brijesh

Reputation: 301

how to handle optimistic locking exception in jpa

What is most suitable way to handle optimistic locking in jpa. I have below solutions but don't know its better to use this.

  1. Handling exception of optimistic locking in catch blocking and retrying again.
  2. Using Atomic variable flag and checking if its processing then wait until other thread finish its processing. This way data modification or locking contention may be avoided.
  3. Maintaining queue of all incoming database change request and processing it one by one.

Anyone please suggest me if there is better solution to this problem.

Upvotes: 0

Views: 3914

Answers (1)

Thomas Stets
Thomas Stets

Reputation: 3035

You don't say why you are using optimistic locking.

You usually use it to avoid blocking resources (like database rows) for a long time, i.e. data is read from a database and displayed to the user. Eventually the user makes changes to the database, and the data is written back.

You don't want to block the data for other users during that time. In a scenario like this you don't want to use option 2, for the same reason.

Option 1 is not easy, because an optimistic locking exception tells you that something has changed the data behind your back, and you would overwrite these changes with your data. Re-trying to write the data won't help here.

Option 3 might be possible in some situations, but adds a lot of complexity and possible errors. This would be my last resort by far.

In my experience optimistic locking exceptions are quite rare. In most cases the easiest way out is to discard everything, and re-do it from start, even if it means to tell the user: sorry, there was an unexpected problem, do it again.

On the other hand, if you get these problems regularly, between two competing threads, you should try to avoid it. In these cases option 2 might by the way to go, but it depends on the scenario.

If the conflict occurs between a user interaction and a background thread (and not between two users) you could try to change the timing of the background thread, or signal the background thread to delay its work.

To sum it up: It mostly depends on your setup, and when and how the exception occurs.

Upvotes: 1

Related Questions