title: Singleton-EJB concurency with a container-managed transaction
body: <p>I have a Singleton-EJB, that reads all objects from a database with a specific state. Then I do something with these objects and set the state to someting else:</p>
  
  <pre><code>@Singleton
  public class MyEJB {
  
      @PersistenceContext(unitName = "MyPu")
      private EntityManager em;
  
      @Lock(LockType.WRITE)
      public void doSomeStuffAndClose() {
          List&lt;MyObj&gt; objects = getAllOpenObjects();
          for (MyObj obj : objects) {
              // do some stuff here...
              obj.setClosed(true);
          }
      }
  
      private List&lt;MyObj&gt; getAllOpenObjects() {
          TypedQuery&lt;MyObj&gt; q = em.createQuery("select o from MyObj o "
              + "where o.closed = false", MyObj.class);
          return q.getResultList();
      }
  }
  </code></pre>
  
  <p>Now, if i would like to ensure that my method cannot be called concurently, I add the annotation <code>@Lock(LockType.WRITE)</code>. But the transaction that sets the states in the database is committed AFTER the lock was released and it is possible that the next caller grabs the same objects again.</p>
  
  <p>How could I prevent this?</p>