users@ejb-spec.java.net

[ejb-spec users] Re: Section 16.15.2 question: is SessionContext obligated to be threadsafe?

From: Marina Vatkina <marina.vatkina_at_oracle.com>
Date: Tue, 21 Aug 2012 17:36:22 -0700

Laird Nelson wrote:
> Section 16.15.2 of the EJB 3.1 specification states in its entirety:
>
> The Container Provider is responsible for providing an appropriate
> EJBContext object to the referencing component. The object
> returned must be of the appropriate specific type for the bean
> requesting injection or performing the lookup—that is, the
> container provider must return an instance of the SessionContext
> interface to referencing session beans and an instance of the
> MessageDrivenContext interface to message-driven beans.
>
>
> Must this EJBContext object be safe for use by multiple threads?

EJBContext in non-singleton beans is accessed only by a single thread,
so it doesn't need to be thread safe. If we use the following text in
the section 4.8.5 Singleton Session Bean Concurrency, it makes it a
developer responsibility to make sure the context is thread safe, if
more than one thread can access that singleton instance at the same time:

"It is legal to store Java EE objects that do not support concurrent
access (e.g. references to Java Persistence entity managers or stateful
session beans) within the singleton session bean instance state.
However, it is the responsibility of the Bean Provider to ensure such
objects are not accessed by more than one thread at a time."

>
> In a stateless session bean that injects a SessionContext, the object
> /must/ obviously be thread safe, since a stateless session bean is
> prohibited from using synchronization primitives, and hence would be
> unable to use the synchronized keyword to control access to this object.
>
> But what about in a singleton session bean with bean-managed
> concurrency? Suppose such a bean has a SessionContext injected into
> it. Must that bean synchronize access to the SessionContext? Or is
> the SessionContext guaranteed by some other part of the specification
> to be thread safe?
>
> (Related StackOverflow question
> here: http://stackoverflow.com/questions/12028144/is-a-javax-ejb-sessioncontext-injected-into-a-bean-managed-concurrency-singleton)
>
> (Related GlassFish forum post
> here: http://www.java.net/forum/topic/glassfish/glassfish/sessioncontext-inherently-thread-safe-even-bmc-singleton)
>
> (Background: http://ljnelson.posterous.com/java-ee-compatible-abstractexecutorservice-im-6803)
>
> Best,
> Laird
>
> --
> http://about.me/lairdnelson
>