persistence@glassfish.java.net

RE: thread-safety

From: Doug Clarke <douglas.clarke_at_oracle.com>
Date: Fri, 1 Sep 2006 11:21:37 -0400

Daniel,

The specification states in section 5.2:
"An entity manager may not be shared among multiple concurrently executing threads. Entity managers may only be accessed in a single-threaded manner."

The underlying TopLink implementation is thread safe but I cannot guarantee the JPA implementation on top of it is as it is not required to be.

Doug Clarke
Principal Product Manager
Oracle TopLink
douglas.clarke_at_oracle.com
  -----Original Message-----
  From: Daniel Cavalcanti [mailto:dhcavalcanti_at_gmail.com]
  Sent: Friday, September 01, 2006 11:13 AM
  To: persistence_at_glassfish.dev.java.net
  Subject: thread-safety


  Hello,

  Quick question: Is the EntityManager thread safe?

  For example,

  class Foo {

      private EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
      private EntityManager manager = emf.createEntityManager();
      
      // method accessed by several concurrent threads
      public void foo() {
          
          try {
              manager.getTransaction().begin();
              // TODO: do somethinf
              manager.getTransaction().commit();
          } catch(Exception e) {
              manager.getTransaction().rollback();
          }
         
      }
      
  }

  thanks,
  Daniel.