This is a common scenario where you want to generate a database controlled unique sequence for your application business requirement i.e order number generator, id generator, claim number generator etc. Considering that your application may have distributed architecture with multiple JVMs and a single database, we do not have option of using JVM level synchronization to ensure thread safety of sequence. The only option is to use database level concurrency control to achieve thread-safety (to resolve issues like lost updates, etc.)
Hibernate (and even JPA 2.0) offers two approaches to handle concurrency at database level - 1. Pessimistic Approach - All the calls to increment sequence in the table will be serialized in this case, thus no two threads can update the same table row at the same time. This approach suits our scenario since thread contention is high for sequence generator. 2. Optimistic Approach - a version field is introduced to the database table, which will be incremented every time a thread updates the sequence value. This does not require any locking at the table row level, thus scalability is high using this approach provided most threads just read the shared value and only few of them write to it.
Read full article from Cracking Java Interviews (Java, Algorithm, Data structure, multi-threading, Spring and Hibernate): How will you create a thread safe table backed unique sequence generator in spring hibernate?
No comments:
Post a Comment