Why is spawning threads in Java EE container discouraged?

LiorH picture LiorH · Feb 10, 2009 · Viewed 52.5k times · Source

One of the first things I've learned about Java EE development is that I shouldn't spawn my own threads inside a Java EE container. But when I come to think about it, I don't know the reason.

Can you clearly explain why it is discouraged?

I am sure most enterprise applications need some kind of asynchronous jobs like mail daemons, idle sessions, cleanup jobs etc.

So, if indeed one shouldn't spawn threads, what is the correct way to do it when needed?

Answer

Robin picture Robin · Feb 10, 2009

It is discouraged because all resources within the environment are meant to be managed, and potentially monitored, by the server. Also, much of the context in which a thread is being used is typically attached to the thread of execution itself. If you simply start your own thread (which I believe some servers will not even allow), it cannot access other resources. What this means, is that you cannot get an InitialContext and do JNDI lookups to access other system resources such as JMS Connection Factories and Datasources.

There are ways to do this "correctly", but it is dependent on the platform being used.

The commonj WorkManager is common for WebSphere and WebLogic as well as others

More info here

And here

Also somewhat duplicates this one from this morning

UPDATE: Please note that this question and answer relate to the state of Java EE in 2009, things have improved since then!