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

Kathir
  • 2,733
  • 12
  • 39
  • 67
  • 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? – Jerry Jan 12 '18 at 15:05

2 Answers2

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
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)

Kathir
  • 2,733
  • 12
  • 39
  • 67