Should I create threads in EJBs in JBoss EAP?

Solution Verified - Updated -

Environment

  • JBoss Enterprise Application Platform (any version)

Issue

  • There is a long runing process within an EJB for which is it desirable to perform parallel processing using threads.
  • Should I create and manage threads in an EJB?
  • What are the recommended alternatives to threading?

Resolution

  • Creation and management of threads by an EJB is not recommended.
  • A common alternative to doing parallel processing in a container is to create Message Driven Beans (MDBs). When there is a step that can be done in parallel or asynchronously, the controller EJB can push a message to the queue and a MDB can pick up the post to the topic and perform needed actions.

Root Cause

  • EJBs are worker threads themselves and controlled by the container.
  • Using multiple threads may lead to unpredictable behavior related to management of transactions and certain resources

See EJB Restrictions for a summary of general restrictions in the context of EJB. The section included below from this article addresses threading specifically:

Why is thread creation and management disallowed?

The EJB specification assigns to the EJB container the responsibility for managing threads. Allowing enterprise bean instances to create and manage threads would interfere with the container's ability to control its components' lifecycle. Thread management is not a business function, it is an implementation detail, and is typically complicated and platform-specific. Letting the container manage threads relieves the enterprise bean developer of dealing with threading issues. Multithreaded applications are still possible, but control of multithreading is located in the container, not in the enterprise bean.

The EJB 3.0 Specification (ejbcore) provides the following guidance in section 21.1.2, Programming Restrictions

  • The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.

These functions are reserved for the EJB container. Allowing the enterprise bean to manage threads
would decrease the container’s ability to properly manage the runtime environment.

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Close

Welcome! Check out the Getting Started with Red Hat page for quick tours and guides for common tasks.