title: Is EntityManager really thread-safe?
body: <p>I'm talking about the basic usage here:</p>
  
  <pre><code>@Stateless
  public class BookServiceBean implements BookService {
    @PersistenceContext EntityManager em;
    public void create(Book book) { this.em.persist(book);}
  } 
  </code></pre>
  
  <p>Googling the above question, StackOverflow says <a href="https://stackoverflow.com/a/13607626/1270789">yes, but no</a> - the accepted answer says Yes, but a followup is No; Spring.io says <a href="http://forum.spring.io/forum/spring-projects/data/24964-is-the-entitymanager-injected-via-persistencecontext-thread-safe" rel="noreferrer">both yes and no</a>, and Adam Bien, who seems to be a Java EE expert, gives an <a href="http://www.adam-bien.com/roller/abien/entry/is_in_an_ejb_injected" rel="noreferrer">unqualified yes</a>.</p>
  
  <p>My own experience with a simple scheduled bean suggests the answer is NO:</p>
  
  <pre><code>@Stateless
  public class TimerTick implements TimerTickAbs, Runnable {
    @PersistenceContext private EntityManager entityManager;
    @Override
    public void run() {
      Query q = entityManager.createQuery("SELECT blah...");
    }
    @Override
    public Runnable runner() {
      return this;
    }
  }
  </code></pre>
  
  <p>Abstract interface:</p>
  
  <pre><code>@Local
  public interface TimerTickAbs {
    public Runnable runner();
  }
  </code></pre>
  
  <p>Started with:</p>
  
  <pre><code>@Resource ManagedScheduledExecutorService managedExecutorService;
  @EJB TimerTick myRunner;
  
  public void startup()
  {
      managedExecutorService.scheduleAtFixedRate(myRunner.runner(), 3, 40, TimeUnit.SECONDS);
  }
  </code></pre>
  
  <p>If I print out the <code>Thread.currentThread().getId()</code>, even though I am still on the same thread between calls, I get:</p>
  
  <blockquote>
    <p>SEVERE: java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManager</p>
  </blockquote>
  
  <p>I know I can do code like <code>@PersistenceUnit private EntityManagerFactory emf;</code> and manage the <code>EntityManager</code> myself, but I'd like to take advantage of all the automatic transaction stuff that <code>@PersistenceContext</code> gives me.</p>