title: Managing the product count in the database
body: <p>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. </p>
  
  <p>There is a Product class with an integer variable <code>productCount</code> 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. </p>
  
  <p>The ORM framework being used is hibernate</p>
  
  <p>Sample code </p>
  
  <pre><code>@Entity
  @Table
  class Product{
     @Column
     private int productCount;
  
     public void addProductToCart(){
       // decrements the product count by 1 &amp; updates the database
     }
  
     public void removeTheProductFromTheCart(){
      // increments the product count by 1 &amp; updates the database
     }
  </code></pre>
  
  <p>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. </p>
  
  <p>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?</p>
  
  <p>I did a little research on this </p>
  
  <p>Possible ways I found were </p>
  
  <ol>
  <li><p>Creating a singleton class for Product. That would ensure that just one instance of product is available throughout the application.</p></li>
  <li><p>Synchronize the <code>addProductToCart</code> &amp;  <code>removeTheProductFromTheCart</code> methods. 
  which would allow only one thread to update the product count &amp; update the db at a time. </p></li>
  <li><p>Use database concurrency control apply some db transaction isolation level, optimistic/pessimistic locking for the <code>productCount</code>. I am using mysql the default isolation level is <code>REPEATABLE_READ</code>.</p></li>
  </ol>
  
  <p>What would be the best approach to deal with this?</p>