users@glassfish.java.net

Re: Rethinking use of _at_ApplicationScope

From: Craig Ringer <craig_at_postnewspapers.com.au>
Date: Tue, 21 Sep 2010 21:24:56 +0800

On 09/17/2010 11:56 AM, glassfish_at_javadesktop.org wrote:
> I don't have a lot of experience with IoC, but I think I have a good structure for my application's use of JPA 2.0. For every @Entity bean, I have a @Model annotated "control" bean that has all the functions I use for querying and updating those entities.
>
> The control bean has no state in it other than the PersistenceContext and the EntityManager, which are injected for me. (nice).
>
> My question is why would I not annotate this control bean as @ApplicationScope?

Concurrency and memory use.

> Since it has no state, and only on persistence context is in use, I could have thousands of sessions all using one instance, instead of each session or each request having its own. Is there any downside to doing this? It may just be my lack of experience but I don't see it.

AFAIK, many threads manipulating one EntityManager at a time = messy
meltdown. @ApplicationScoped isn't going to be pretty there.

Letting the container manage your concurrency issues for you with
individual instances per request/view/session as appropriate will be
much less painful, I suspect.

It'll also help you avoid accumulating lots of in-memory instances of
objects you no longer need or care about. Remember, a JPA provider has
to return the *same* *instance* of an object when a single EntityManager
is asked for an entity multiple times. This means an EntityManager can
never release entities it has fetched until it is closed, detaching all
the entities.

--
Craig Ringer