Amol
Amol

Reputation: 23

Block application thread to read DB while another transaction is in process

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.

Upvotes: 2

Views: 66

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 82008

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.

Upvotes: 1

Related Questions