Excuse me if this question may seem naive but I have come across a scenario where I need to manage the product count in the database of an e-commerce store.
There is a Product class with an integer variable productCount
which signifies the number of available products in the database which is visible to users of the site. Now this class is accessed by several threads or can say several users of the e-commerce site. Everyone is adding or removing the product to his cart.
The ORM framework being used is hibernate
Sample code
@Entity
@Table
class Product{
@Column
private int productCount;
public void addProductToCart(){
// decrements the product count by 1 & updates the database
}
public void removeTheProductFromTheCart(){
// increments the product count by 1 & updates the database
}
As it is clear from the code that I need to keep a concurrency check on the product count in the database to prevent lost updates.
Also if several users are trying to add only single left product in the database. Which user's cart the product should be added to?
I did a little research on this
Possible ways I found were
Creating a singleton class for Product. That would ensure that just one instance of product is available throughout the application.
Synchronize the
addProductToCart
&removeTheProductFromTheCart
methods. which would allow only one thread to update the product count & update the db at a time.Use database concurrency control apply some db transaction isolation level, optimistic/pessimistic locking for the
productCount
. I am using mysql the default isolation level isREPEATABLE_READ
.
What would be the best approach to deal with this?