title: Delivery of JMS message before the transaction is committed
body: <p>I have a very simple scenario involving a <strong>database</strong> and a <strong>JMS</strong> in an application server (Glassfish). The scenario is dead simple: </p>
  
  <pre><code>1. an EJB inserts a row in the database and sends a message.
  2. when the message is delivered with an MDB, the row is read and updated. 
  </code></pre>
  
  <p>The problem is that sometimes the <strong>message is delivered before the insert has been committed</strong> in the database. This is actually understandable if we consider the 2 phase commit protocol:</p>
  
  <pre><code>1. prepare JMS
  2. prepare database
  3. commit JMS
  4. ( tiny little gap where message can be delivered before insert has been committed)
  5. commit database
  </code></pre>
  
  <p>I've discussed this problem <a href="http://forums.java.net/jive/message.jspa?messageID=351867" rel="noreferrer">with others</a>, but the answer was always: <em>"Strange, it should work out of the box"</em>.</p>
  
  <p>My questions are then:</p>
  
  <ul>
  <li>How could it work out-of-the box? </li>
  <li>My scenario sounds fairly simple, why isn't there more people with similar troubles?</li>
  <li>Am I doing something wrong? Is there a way to solve this issue correctly?</li>
  </ul>
  
  <hr>
  
  <p>Here are a bit more details about my understanding of the problem:</p>
  
  <p>This timing issue exist only if the participant are treated in this order. If the 2PC treats the participants in the reverse order (database first then message broker) that should be fine. The problem was randomly happening but completely reproducible.</p>
  
  <p>I found no way to control the order of the participants in the distributed transactions in the JTA, JCA and JPA specifications neither in the Glassfish documentation. We could assume they will be enlisted in the distributed transaction according to the order when they are used, but with an ORM such as JPA, it's difficult to know when the data are flushed and when the database connection is really used. Any idea?</p>