Why my pessimistic Locking in JPA with Oracle is not working

后端 未结 3 585
夕颜
夕颜 2020-12-09 19:06

I\'m trying to implement some kind of semaphores for cron jobs that runs in different JBoss nodes. I\'m trying to use the database (Oracle 11g) as a locking mechanism using

相关标签:
3条回答
  • 2020-12-09 19:50

    I can confirm Ricardos observation. I have several Lock-Modes tested with a H2-Database, and all worked as expected. Neither of the pessimistic Lock-Modes worked correctly in combination with an Oracle database. I did not try optimistic locking, but it's amazing that there's a lockmode that doesn't work with the top dog at all.

    0 讨论(0)
  • 2020-12-09 19:54

    Set locking mode to PESSIMISTIC_READ, because you need that second server knew about changes of first server before changing data.

    0 讨论(0)
  • 2020-12-09 20:01

    Finally i managed to make it work but with some modiffications. The idea is to use LockModeType.PESSIMISTIC_FORCE_INCREMENT instead of PESSIMISTIC_WRITE. Using this lock mode the Cron Jobs behave as follows:

    1. When the first job makes the select for update everything goes as expected but the version on the object changes.
    2. If another job tries to make the same select while the first is still on its transaction, JPA launches a OptimisticLockException so if you catch that exception you can be sure that it was thrown for a read lock.

    This solution has various counterparts:

    1. SynchronizedCronJobTask must have a version field and be under version control with @Version
    2. You need to handle OptimisticLockException, and it should be catch outside the transactional service method in order to make rollback when de lock happens.
    3. IMHO is a non elegant solution, much worse than simply a lock where the Cron Jobs wait for the previous Jobs to finish.
    0 讨论(0)
提交回复
热议问题