J2EE程序中如何正确的管理自己的custom线程

本文探讨了为何不应在J2EE程序中直接创建线程,强调了容器对线程管理的重要性,以避免生命周期和资源管理问题。介绍了在servlet和bean中如何正确管理custom线程,包括利用Executor服务和在销毁时妥善关闭线程池。
摘要由CSDN通过智能技术生成

在这里,我们要讨论的话题包含了一个明确的前提,在J2EE程序使用线程。必须说明的是,在我们学习如何编写J2EE程序的时候,就被明确告知了,不允许在J2EE程序中自己创建和管理线程。具体可以参见http://www.oracle.com/technetwork/java/restrictions-142267.html

为何不能在J2EE程序中创建线程

Container control.

The container is responsible for coordinating system services, controlling threads, managing security, bean lifecycle, and so on. Some restrictions prevent enterprise bean classes from interfering with proper container operation. For example, see the following discussion on threads.

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, no**重点内容**t in the enterprise bean.

也就是说,我们应该专注于业务逻辑,而让EJB的container来负责管理线程 (这里的不应该狭义的理解为只有EJB的情况下才这样做,当我们使用其他的容器管理框架,比如spring的时候,也应该遵循类似的约束)。

另外一段关于为何不能在J2EE程序中创建线程的描述,可能会更易于理解:

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.

因此,当你打算在enterprise bean中自己创建线程的时候,一定要三思,是否我们可以通过创建可以被container管理的bean,来完成你需要创建线程才能完成的任务

当然,如果你非得在J2EE里面创建线程,而且你也解决了上面提到的没法获取thread的InitialConext或者JNDI lookups什么的问题,那么你就必须注意一下我提到的这点:

我们知道,J2EE程序是部署在容器服务器上的,无论你用的什么Jboss(wildfly),weblogic, websphere等,都会支持动态部署。我们可以在不重启容器服务器的情况下,随意的deploy和undeploy各种J2EE程序。为什么我们需要让container来管理我们的程序,其中一点就是只有containter能够安全的处理各种bean的lifecycle,何时创建,何时销毁,如何释放各种资源。当你自己创建了一个线程,特别是一个拥有while循环的线程


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值