I want to use more than one app instance for my Java application. The aplication works with DB: writes and reads data. I'd like to use Hibernate with L1 caching (Session level) only. My question is: should I sync cache for each instance or there's no need to worry about synchronization of the caches?
1 Answers
It's all depends on what is your application is about ?
Say you are running an e-commerce shop, in the admin panel, there is a service for managing products. Two separate user opens the same product page and update them. There is nothing wrong about it (unless you have some specific business case)
Another scenario is, you are tracking the inventory of products. Say you maintain a count of each product. When you add product, this count get increased and when you sell products this count get decreased. This operation is very sensitive and require some sort of locking. Without locking following scenario can happen
| Timestamp | App Instance A | App Instance B |
|---|---|---|
| T1 | Reads and found 10 product | Reads and found 10 product |
| T2 | Removes Two product and write 8 | Does nothing |
| T3 | Done nothing | Add Two product and write 12 |
Thus it now tracks wrong count in the database.
To tackle these scenarios there are mostly two kind of locking mechanism
- Optimistic locking
- Pessimistic locking
To learn more about these sort of locking read here.
A simple way to implement the optimistic locking in hibernate is using the version column in the database and application entity.
Here is a good article about the entity versioning.
- 6,821
- 2
- 31
- 41