Announcement Announcement Module
Collapse
No announcement yet.
EntityManager in Singleton and Concurrency Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • EntityManager in Singleton and Concurrency

    Hi,

    If I use spring to inject an EntityManager instance into a singleton bean, won't it lead to concurrency issues as EM is not thread safe? If not, how does Spring manage to avoid it?

  • #2
    I suggest you read the reference gudie explaining spring and JPA.

    The spring based EntityManager (which is basically a proxy) is a thread safe one.

    Comment


    • #3
      Thanks for the help. It clarified a lot.

      Comment


      • #4
        Originally posted by Marten Deinum View Post
        I suggest you read the reference gudie explaining spring and JPA.

        The spring based EntityManager (which is basically a proxy) is a thread safe one.
        Call me stupid, but I don't understand how it is safe to use.

        The EntityManager is the JPA version of the Hibernate Session, and a Session is not threadsafe.

        @Chandru
        But why would you inject a EntityManager in a singleton? In most (all?) cases you want to create a new EntityManager for every transaction (and this can be completely automated by using an transaction aspect).

        So am I missing something, or do the provided question and answer make no sense.

        Comment


        • #5
          EntityManager appears to be thread-safe

          I was really unsure about this issue and as a result was planning to implement my Web Services framework (which does not include JEE) using a EntityManagerFactory and have all the service classes get their own EntityManager instance.

          Howerver, after stepping into the source code, I discovered that what Spring does is load-time weave the class that needs an EntityManager (I used the @PersistenceContext annotation to indicate injection) with CGLIB. Then on any method invocation of the injected EntityManager, a new EntityManager instance is provided, thereby ensuring that there are no concurrency issues.

          You can verify this behavior by adding debug level logging in Log4J for the following package:
          org.springframework.orm.jpa

          You wll see a message saying "Creating new EntityManager for shared EntityManager invocation" for each method invocation on the EntityManager.

          The Spring class that performs the "magic" is org.springframework.orm.jpa.SharedEntityManagerCre ator. If you look at the code, it also closes the EntityManager right after its use.
          Last edited by ChrisMuller; Feb 24th, 2009, 07:50 PM.

          Comment

          Working...
          X