title: JPA: Read and persist in one transaction while blocking Read in different thread
body: <p>My use case are two entities in 1..N relationship, let's say Box and Items in Box. Box has an attribute "capacity" which specify how much Items I can have in Box.</p>
  
  <p>What I'm actually doing. I select count of all Items in Box and when the number of Items is less than the Box.capacity I persist the Item.</p>
  
  <p>Problem is when I access my method concurrently. Calling method twice in a same time will cause that both reads can be run concurrently and when it comes for write phase, both thread write the Item into database.</p>
  
  <p>My code:</p>
  
  <pre><code>@Entity
  public class Box {
      private int capacity;
  }
  
  @Entity
  public class Item {
      @ManyToOne
      Box box;
  }
  
  @Stateless
  public class BoxManager {
      @PersistenceContext
      EntityManager em;
  
      public Item persistItem(Item item) {
          Box box = item.getBox();
          Query query = em.createQuery("SELECT COUNT(i) FROM Item i WHERE i.box = :box");
          query.setParameter("box", box);
  
          int itemCount =  ((Number)typedQuery.getSingleResult()).intValue();
  
          // We can simulate concurrent problem putting Thread.sleep() here.
  
          if (itemCount &lt; box.getCapacity()) {
              return em.persist(item);
          } else {
              return null;
          }
      }
  }
  </code></pre>
  
  <p>I'm calling method <code>persistItem</code> concurrently.</p>
  
  <p>The question is how can I prevent another thread to read the incorrect number of Items before the first thread persist the first Item?</p>
  
  <p>Problematic scenario is:</p>
  
  <pre><code>Thread 1: Reads count of items
  Thread 2: Reads count of items
  Thread 1: Writes Item to database
  Thread 2: Also Writes Item to database
  </code></pre>
  
  <p>Or is there any better way how to handle this? How to check count of entity and persist it without the concurrency problems?</p>