Why is spawning threads in Java EE container discouraged?

前端 未结 9 1962
清歌不尽
清歌不尽 2020-11-22 04:50

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 do

9条回答
  •  梦谈多话
    2020-11-22 05:53

    For EJBs, it's not only discouraged, it's expressly forbidden by the specification:

    An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances.

    and

    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.

    The reason is that EJBs are meant to operate in a distributed environment. An EJB might be moved from one machine in a cluster to another. Threads (and sockets and other restricted facilities) are a significant barrier to this portability.

提交回复
热议问题