Active MQ uses pessimistic locking at the database table level when two instances of activeMq are configured over a single database with failover feature.
No two threads shall pick up the same task from database table using Hibernate
Carvia Tech | December 31, 2017 | 1 min read | 9 views
This is a typical scenario of db persisted queue where only one thread shall pick up a given task in the table.
Multiple Threads poll same table for incoming tasks, how will you make sure that no two threads pick up the same task?
There are two approaches to handle this scenario:
Pessimistic Locking at DB record level where only one transaction is allowed to access the record at a given time.
Optimistic locking where version number of task record is updated once a thread picks up the record. When second thread tries to increment the version, it fails during the dirty checking and transaction is rolled back. This thread needs to retry picking up the record one more time.
We will discuss both the approaches with explanation:
Implementing a shared database counter that can be incremented from multiple threads. To make it thread-safe, either optimistic locking or pessimistic locking has to be used to ensure that no two threads get the same global counter value.
Top articles in this category:
- Table backed global counter in spring hibernate
- Prevent Lost Updates in Database Transaction using Spring Hibernate
- N+1 problem in Hibernate & Spring Data JPA
- Spring RestTemplate Basic Authentication
- Disable SSL validation in Spring RestTemplate
- Spring Boot 2.0 Reactive Web Performance Metrics
- Spring Boot WebClient Basic Authentication