Question

I came across this blog below, concerning Servlets and injecting EJBs into them. The author is writing from a standards point-of-view.

http://tamanmohamed.blogspot.ie/2012/03/jpa-why-we-need-to-specifies-type-level.html http://tamanmohamed.blogspot.ie/2012/03/jpa-thread-safety-when-injecting.html

"injecting EJB 3 stateful beans into servlet instance fields is not thread-safe. Along the same line, injecting EntityManager with @PersistenceContext into servlet instance variables is not thread-safe, either. EntityManager is just not designed to be thread-safe."

Anyhow, I am starting to get worried about the code I'm writing with a colleague in the Glassfish-3.1.2 implementation. See below. I thought it was similar to code I've seen in Duke tutoring tutorial so it should be o.k. (where FaceServlets call a stateless Request bean with @PersistnceContext EntityManager.)

However I guess I'm assuming the container-managed EntityManager is capable of coping with lots of concurrent calls of a stateless bean called by many instances of servlets.

Is this a correct assumption for Glassfish-3.1.2 with an Oracle database ? It seems to work fine so far, but maybe it won't under heavy loads.

thanks in advance for any insights. Sorry I'm such a newby to this. Fiona

Servlet
{
@EJB
private StatelessbeanBlah
:
}

@Stateless
StatelessBeanBlah
{
@PersistenceContext(unitname = "...")
private EntityManager em;
Was it helpful?

Solution

There is some confusion in your question, because thread-safety of EntityManager instances depend on whether you are using Container-Managed Entity Managers or Application-Managed Entity Managers. In the first case,

an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction API (JTA) transaction.

...

By automatically propagating the persistence context, application components don’t need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.

(ref. Managing Entities, Java EE 6 Tutorial)

Try to define a JTA-aware data source in your persistence.xml file, and see what happens. I am not keen in injecting a persistence context into a servlet, because when developing Java EE 6 web applications there is JSF, and you don't need to create your own servlets in most of the situations, and I am quite new to this technology, too. However, injecting a persistence context into a managed bean or an enterprise bean (like a Stateless EJB), with a JTA-aware data source, is absolutely fine and thread safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top