Control Concurrent Access to Models in Hybris
1. Overview
Concurrent access to Models in Hybris project occurs frequently during an access to shared Models by different threads simultaneously, like StoreModel
or StockLevelModel
.
In this article, I will show you how to control concurrent access to a Model in Hybris, using ModelService.lock()
.
The ModelService.lock()
uses SELECT FOR UPDATE
statement to lock a Model for a single transaction, other transactions will be blocked from updating this Model.
The locked Model will be released when the transaction is committed or rolled back.
Note that HSQLDB doesn’t support row locking.
2. Implementation
The lock()
method should be used whiten a transaction.
public void lock_stocklevel_test()
{
StockLevelModel stockLevel = ...
final Transaction transaction = Transaction.current();
transaction.begin();
try
{
// lock stocklevel
modelService.lock(stockLevel.getPk());
// update stocklevel here...
// save stocklevel
modelService.save(stockLevel);
// commit to release the lock
transaction.commit();
}
catch (final Exception e)
{
transaction.rollback();
}
}
3. Conclusion
You should avoid using the lock() method whenever it’s possible, because it may bring you some unnecessary problems, unless you really know what you are doing !
Software Craftsmanship, Stackextend author and Full Stack developer with 6+ years of experience in Java/Kotlin, Java EE, Angular and Hybris…
I’m Passionate about Microservice architectures, Hexagonal architecture, Event Driven architecture, Event Sourcing and Domain Driven design (DDD)…
Huge fan of Clean Code school, SOLID, GRASP principles, Design Patterns, TDD and BDD.