2

Could someone help me with the possible hibernate exceptions when two threads update the same Object?

ex: employee with name "a", age "30" and address "test" thread1 tries to update "a" to "b" and thread2 tries to update "a" to "c"

Thanks in advance, Kathir

1
  • In my case thread1 is updating a to b and thread2 is updating 30 to 35, but both are writing into the same row and I am getting a deadlock. Any help on this? Commented Jan 12, 2018 at 15:05

2 Answers 2

4

If your object is a Hibernate entity, then two threads shouldn't have a reference to the same object in the first place.

Each thread will have its own Hibernate session, and each session will have its own copy of the entity. If you have a field annotated with @Version in your entity, for optimistic locking, one of the thread will get an OptimisticLockException. Otherwise, everything will go fine, and the last thread to commit will win.

Sign up to request clarification or add additional context in comments.

Comments

2

Thanks for the answers and below are the comments after observation and analysis

  1. We can also do a conditional update with where clause in the query and use executeUpdate() method. Ex: The Hibernate - Query - executeUpdate() method updates and return the number of entities updated. So if the executeUpdate() returns "zero" it means the row has been already updated by another thread. (No Exception)

  2. Using @Version. (OptimisticLockException)

  3. Using Row Level DB lock. (DB Exception)

  4. Using Synchronization. (Java Synchronization Exception)

1 Comment

can you help to understand point#4, what is Synchronization exception?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.