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