Adam Bien's Weblog
Can I Start Threads In EJBs?
Starting threads in EJB container is clearly prohibited:
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. [EJB 3.1 spec, page 599]
An application server usually does not actively monitors "wild thread creation" so you can create and start as many threads you like. In fact an application server is not even capable to prevent that. However, Java SE itself is can effectively prevent starting thread by activating the SecurityManager and configuring the following permission: http://docs.oracle.com/javase/6/docs/api/java/lang/SecurityManager.html#checkAccess(java.lang.ThreadGroup)
Although this permission is not enforced per default, operations could set such rules at any time.
With default installation you could create threads, but you shouldn't. The reasons are:
- It is hard to control thread creation effectively. Each thread consumes memory. Uncontrolled creation leads to OutOfMemoryError
- Manually created threads are not monitored
- Consistency is harder to achieve--you and container are going to access a piece of code concurrently
- Throttling is harder to implement
- You are going to write superfluous code: with JavaEE it is surprisingly easy to start a managed thread. Even a JCA based solution with JavaEE 6 for thread management is relatively easy to implement. With JavaEE 7 you get even more control by injecting an ExecutorService.
Keep in mind that, Servlet Container, JMS server, EJB container, CDI container, JMX beans and JCA containers are running in the same process. Thread creation is only prohibited in the EJB spec. To make the container more robust, it should be prohibited in the whole server process. Moving the thread creation from the EJBs to e.g. Servlets is not a reasonable solution :-)
NEW Special Events: From HTML 5 over Java EE App Building and NoSQL / Distributed Computing to Microservices