0

Hello Im trying to understand an issue related to pessimistic locks when running 3 instances of my application. The application has, among other stuffs, a spring schedule which runs every 3 hours and I need the business logic inside the function annotated with @Scheduled to run successfully just in one of the instances.

To accomplish this, at the beginning of this function, Im trying to lock a specific indexed row in a table just like that

@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.SERIALIZABLE)
.....
LockTableEntity entity = this.em.find(LockTableEntity.class, 1L);
this.em.lock(entity, LockModeType.PESSIMISTIC_READ);
//this.em.lock(entity, LockModeType.PESSIMISTIC_WRITE); I have tried this as well!!
entity.setDatLock(LocalDateTime.now());
this.em.merge(entity);
.....

The issue Im facing is from time to time I can get a lock in one or two of the instances - throwing exceptions properly LockAcquisitionException and rolling back transaction - but not always in two instances as I expected it to happen, so just one of those 3 should run 'til the end!

So I would like to know what Im doing wrong? Am I misunderstanding the lock process any how?

Stack:

  • Spring Boot 2.5.2
  • Hibernate Core 5.4.32
  • Database MySQL 5.7
  • MySQL connector 8.0.25
escapistabr
  • 101
  • 3

1 Answers1

0

You should be using LockTableEntity entity = em.find(LockTableEntity.class, 1L, LockMode.PESSIMISTIC_WRITE);. It's impossible to acquire the same exclusive lock multiple times. Maybe one of your transactions times out?

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58