Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PersistenceContext EntityManager thread-safety in Spring and Java EE

EntityManager is not thread-safe by definition. Servlets specs says that in non-distributed environment and without implementing SingleThreadModel, there is only one servlet instance per definition.

Therefore, in Java EE when you inject an EntityManager through the @PersistenceContext into Servlet's field - it's not thread safe:

public class MyServlet extends HttpServlet {

    // Not thread-safe, should be using EMF instead.
    @PersistenceContext
    private EntityManager em;
}
  1. Is this correct to say that even though the default scope of Spring beans is singleton, the EntityManager is thread-safe as the Spring uses ThreadLocal to bind its transaction and EntityManager to it?

  2. Is the above Servlets example still valid in Spring? Is it still not thread-safe?

  3. Does the ThreadLocal approach works only for Spring managed beans and plain servlet is not one of those?

  4. As far as I remember, it's the container responsibility to inject the EntityManager. In Glassfish Java EE implementation, it was the application server who discovers the @PersistenceContext as injection point.
    How does it look like in Spring? Is the Spring Framework responsible for discovering those annotations or it's responsibility of the JPA implementor?

like image 959
Piotr Nowicki Avatar asked Apr 30 '12 08:04

Piotr Nowicki


People also ask

Is the JPA EntityManager object thread safe?

No, an EntityManager is NOT thread safe.

Is hibernate EntityManager thread safe?

The EntityManagerFactory instances, and consequently, Hibernate's SessionFactory instances, are thread-safe.

Is persistence context thread safe?

Actually they share the same proxy EntityManager which delegates calls to the same persistence context. Another proof is that there is no any mention of thread safety in EntityManager javadoc. So while you stay inside Java EE container you shouldn't care about concurrency access to EntityManager.

Is JPA thread safe?

You don't need to make those methods synchronized, they are thread safe as it is.


1 Answers

Question 2, 3, and 4 -- Spring does not pay attention to any class that is not a Spring Bean. Therefor Spring does not pay attention to you MyServlet class. Therefore the answer for

  • 2) is no
  • 3) only Spring managed Beans
  • 4) it is Springs responsibility, because Spring is the Container

For Question 1). It works this way, so the usage of an Spring Injected Entity Manager is effective thread save.

like image 77
Ralph Avatar answered Sep 18 '22 08:09

Ralph