Laird Nelson
Laird Nelson

Reputation: 16238

Is a javax.ejb.SessionContext injected into a bean-managed-concurrency Singleton bean threadsafe?

I have a @Singleton session bean. The bean is annotated with @ConcurrencyManagement( ConcurrencyManagementType.BEAN).

It has a SessionContext injected into it via the @Resource annotation.

Is this SessionContext inherently threadsafe (since it is a container-produced object that is also used in non-bean-managed-concurrency situations), or does my bean have to synchronize on a lock to access and manipulate it? Section 16.15.2 of the EJB 3.1 specification makes no mention of the thread safety of injected EJBContext objects.

Upvotes: 1

Views: 2507

Answers (2)

Laird Nelson
Laird Nelson

Reputation: 16238

From a posting by Marina Vatkina on the [email protected] mailing list:

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."

Upvotes: 1

Brett Kail
Brett Kail

Reputation: 33946

The context object must be thread-safe, and it almost certainly implements this using thread-local variables (in fact many of the mysterious parts of Java EE can be understood once you realize the containers are just manipulating thread-local variables: java:comp, security, transaction, etc.). Otherwise, there's no other way for the EJB container implementation to return a reliable result from getInvokedBusinessInterface, wasCancelCalled, etc.

For example, imagine an EJBContext implementation that is not thread-safe; i.e., it has a member variable invokedBusinessInterface and a setInvokedBusinessInterface method that the EJB container would call prior to calling the bean method. In that case, if two singleton methods were called concurrently, one of the threads would necessarily get the wrong answer from getInvokedBusinessInterface, and there's no amount of synchronization that the bean method could apply that would solve this problem.

Upvotes: 1

Related Questions