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:

  1. Pessimistic Locking at DB record level where only one transaction is allowed to access the record at a given time.

  2. 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:

ActiveMQ uses Pessimistic Locking

Active MQ uses pessimistic locking at the database table level when two instances of activeMq are configured over a single database with failover feature.

Similar Problems

  1. 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:
  1. Table backed global counter in spring hibernate
  2. Prevent Lost Updates in Database Transaction using Spring Hibernate
  3. N+1 problem in Hibernate & Spring Data JPA
  4. Spring RestTemplate Basic Authentication
  5. Disable SSL validation in Spring RestTemplate
  6. Spring Boot 2.0 Reactive Web Performance Metrics
  7. Spring Boot WebClient Basic Authentication

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.