-->

Does jboss handle managed Entity Manager concurren

2019-04-13 08:21发布

问题:

It seems that the Entity Manager instance jboss manages and provides is a proxy to the actual implementation bound to a persistence context.

This actual implementation gathers the isolation provided by JTA transactions (per transaction contexts).

That makes me think I don't need to worry about concurrency issues when dealing with the proxy instance.

Maybe I can even cache this proxy instance if I decide to bring it from JNDI lookups instead of container injection?

Is that reasonable?

回答1:

The container is responsible for scanning for @PersistenceContext annotations and injection of EntityManagers. It can proxy the instances of EntityManager.

In EJB, where the container is responsible for dependency injection, you can be sure that you're thread-safe. The persistence context will be shared between multiple components within the same transaction.

However, if you inject this EntityManager using @PersistenceContext in Servlets environment (where the concurrency is a concern), you're not thread-safe. You should use @PersistenceUnit instead. You can refer to this part of the JBoss 7 JPA Reference Guide:

Keep in mind that the entity manager is not expected to be thread safe (don't inject it into a servlet class variable which is visible to multiple threads).

Some time ago I've summed up what I know about Persistence Context sharing between JTA transactions and proxying of EntityManagers by the container and published it here. I hope you'll find it useful.