adam bien's blog

Is in an EJB injected EntityManager thread-safe? 📎

You can inject EntityManager directly into EJBs. But: is it thread safe?:


@Stateless
public class BookServiceBean implements BookService {


  @PersistenceContext EntityManager em;

  public void create(Book book) { this.em.persist(book);}

 } 

It is, the EJB 3.1 specification, JSR-318, page 82 explains the reasons:

"…The container serializes calls to each stateful and stateless session bean instance. Most containers will support many instances of a session bean executing concurrently; however, each instance sees only a serialized sequence of method calls. Therefore, a stateful or stateless session bean does not have to be coded as reentrant…"

"…The container must serialize all the container-invoked callbacks (that is, the business method interceptor methods, lifecycle callback interceptor methods, timeout callback methods, beforeCompletion, and so on), and it must serialize these callbacks with the client-invoked business method calls..."

Working with EJBs without any further configuration is thread-safe regardless whether you are invoking one method or multiple methods concurrently. The container cares about the serialization of calls.

Big thanks to Dean for this question!