title: How to avoid race conditions on product sales with JPA and Hibernate
body: <p>I am using Java Spring Framework and Hibernate. I am doing a e-commerce web application where public user is able to purchase product from the web app. Each product will have a quantity count. </p>
  
  <p><strong>Issue</strong></p>
  
  <p>I want to prevent the scenario where two concurrent users purchase the same product is left with quantity value 1. In this case, only the first user should get to purchase the product while the second user should receive a "no stock available" message.</p>
  
  <p><strong>Workflow</strong></p>
  
  <p>I intend to decrement the quantity count and then send the purchase information to the payment gateway. If payment gateway encounters payment issue, I will increment the quantity count. The lock will be released before purchase info is sent to payment gateway.</p>
  
  <p>So my question is, </p>
  
  <p>1) I would like to confirm <a href="https://stackoverflow.com/questions/16159396/how-to-enable-lockmodetype-pessimistic-write-when-looking-up-entities-with-sprin">this answer</a> on pessimistic locking does help solves my issue.</p>
  
  <p>2) Is my workflow ok? Is there a better way to do this?</p>