1
votes

At quarkus samples i see that ApplicationScoped bean used as service class with EntityManager injection.
As i know (JEE) EntityManager is not thread safe, and ApplicationScoped beans also not. It looks like we are sharing same entity manager between requests if we inject entity manager into ApplicationScoped bean.
If ApplicationScoped bean is thread safe then we can accept only one request at same time. I cant understand why we are using ApplicationScoped instead of RequestScoped beans with EntityManager injection.

1

1 Answers

2
votes

As you can see, Quarkus, like other projects that work with JPA constructs, does quite a lot behind the scenes to make sure that the contextual reference you, as an end user, receive behaves safely and properly.

(Disclaimer: I am not a Quarkus expert, but this particular pattern of delegating EntityManager operations to different underlying EntityManager delegates depending on transaction statuses, synchronization-related and other concerns is common across the application servers that came before it as well.)

Injecting so-called "container-managed" EntityManagers that behave in the way that people intuitively expect them to is reasonably tricky. You are correct to be careful as an end user in this area: indeed, an EntityManager that you receive from EntityManagerFactory#createEntityManager() is not thread-safe. But that's not what is injected into these kinds of slots. For example, EntityManagers injected in this way will do other exciting things like take part in JTA transactions automatically, and those transactions are inherently thread-specific, so some degree of thread safety has to be going on—and so on and so forth. Clearly there's more occurring here, then, than a simple injection of an application-managed EntityManager.

The takeaway is: the EntityManager reference that an ApplicationScoped bean receives is provided in such a way that it is thread-safe.