Control Concurrent Access to Models in Hybris

Hybris Logo

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 !

 

4 2 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x