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 !
Solution Architect with 10+ years of experience across full-stack development, DevOps, and enterprise software design. Expert in building scalable architectures, CI/CD pipelines, and internal developer platforms using tools like GitHub Actions, Terraform, Kubernetes (AKS), Azure, and Prometheus. Strong hands-on background in Java, Spring, Node.js, and event-driven systems (Kafka, Mulesoft). Passionate about developer experience, software quality, and platform engineering