users@glassfish.java.net

Re: EJBContext: thread safe?

From: Cheng Fang <cheng.fang_at_oracle.com>
Date: Fri, 19 Aug 2011 10:27:23 -0400

Hi Laird,

In EJB apps concurrency is managed by the container, and application
developers don't need to worry about concurrency issues. Singleton
sessioin bean in EJB 3.1 adds some flexibility in terms of bean-managed
concurrency, but the concurrency model for application developers is
still the same. I would consider EJBContext immutable and thread-safe.

As long as your entity listeners are accessed as part of EJB invocation,
then you can lookup and make use of EJBContext.

-cheng

On 8/18/11 5:01 PM, Laird Nelson wrote:
> I am doing something along the lines of
> http://www.mindbug.org/2008/04/automatic-tracing-of-entity-changes.html.
> However, I want to ensure I am careful to be thread safe.
>
> EntityListeners do not have a lifecycle (that is, their lifecycle is
> undefined). So a container might create them anew each time, or
> create a single instance, or....
>
> In order to detect if there is a calling principal available, I will
> be using an InitialContext to look up the EJBContext. I have this
> operation's thread safety covered; I am creating the InitialContext in
> a static initializer and assigning it to a public static final reference.
>
> Next, I am careful to synchronize on that context when I call lookup
> on it. So far so good.
>
> The object I am looking up in it is an EJBContext. I need to call
> getCallerPrincipal on it if it is non-null.
>
> My question is: is this object thread safe? Should I perform the
> getCallerPrincipal() call while I have the lock on the
> InitialContext()? That would ensure that no two threads can access
> the InitialContext, retrieve the EJBContext and invoke a method on it
> simultaneously. This could be slow.
>
> My suspicion is that EJBContext must be thread safe, or it could not
> reliably be injected into a stateless session bean via the @Resource
> annotation and used without synchronization--but of course that's
> exactly how it IS used in every example I've ever seen, even in the
> specification.
>
> So: is a container's implementation of EJBContext guaranteed to be
> thread safe? If not, what should I lock on?
>
> Thanks,
> Laird
>
> --
> http://about.me/lairdnelson
>