2

I am having multi threaded application running on multi tenant (separate physical boxes). One of functionality is to update balances for a customer in this scenario if there are two transactions Tr1 and Tr2 coming on separate tenants at same time t1 then its not updating balances correctly. i cant synchronize this as its a multi tenant so boundaries are JVM on a single machine.

Technologies : Spring, hibernate and MS SQL.

I want to block the application thread tr2 (thread on tenant 1) to read the data (of-course for same customer) and process it if tr1 (Thread on another tenant) thread is already working on it.

Amol
  • 23
  • 3
  • What does "its not updating balances correctly" mean? Do you have a version column and thereby optimistic locking enabled? – Jens Schauder Sep 07 '18 at 06:21
  • No i don't have version column in my table. Balance not getting updated means, if starting balance is $7 and transaction tr1 of $2 & tr2 of $3 then after both updates balance is sometimes either $5 or $4, where expected closing balance is $2. – Amol Sep 07 '18 at 07:30

1 Answers1

1

You can use one of two approaches:

Optimistic locking: JPA will not create extra locks but use a version column in order to make sure that the value it is updating is the same did load originally and throw an exception if that is not the case.

You can simply enable that by adding a version attribute, i.e. a column with an @Version annotation. Of course, you will have to catch the resulting OptimisticLockException and act accordingly (possibly trying again).

Pessimistic locking: JPA will create a lock on the database row so nothing can change it until JPA commits.

See the reference documentation of Spring Data JPA.

Here is a related question about how to achieve that.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348