Why is spawning threads in Java EE container discouraged?

前端 未结 9 1731
清歌不尽
清歌不尽 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:48

    I've never read that it's discouraged, except from the fact that it's not easy to do correctly.

    It is fairly low-level programming, and like other low-level techniques you ought to have a good reason. Most concurrency problems can be resolved far more effectively using built-in constructs like thread pools.

    0 讨论(0)
  • 2020-11-22 05:52

    Threads are prohibited in Java EE containers according to the blueprints. Please refer to the blueprints for more information.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题