Using @Transactional for thread safety

My question is, as soon as the @Transactional annotation controls the execution of code and transactions. To properly install the Spring application and the following code:

@Transactional public void withdraw(int amount) { if(isEnoughFunds(amount)) { decreaseFunds(amount); } } 

Is the following scenario possible?

  • funds == 100; quantity == 100
  • thread A enters output / transaction A starts
  • thread A executes isEnoughFunds, which evaluates to true
  • thread B enters shutdown / transaction B starts
  • thread B executes isEnoughFunds, which evaluates to true
  • thread A performs a reduction Funds / thread A blocks a db write
  • thread B waits for thread A to commit the transaction and lock the write lock.
  • thread A completes the output / transaction A completes
  • thread B performs a reduction Funds / thread B blocks writing db
  • thread B completes the output / transaction B commits
  • funds == -100

If possible, how would you prevent this?

+7
source share
1 answer

Yes, it is possible, depending on the level of insulation. To prevent this, you can explicitly get a read lock from the database before calling ifEnoughFunds (). The lock will be released at the end of the transaction. In this case, thread B will always wait for the transaction of thread A to commit.

+3
source

All Articles