简体   繁体   English

MessageDrivenBean中的finalize方法

[英]finalize method in MessageDrivenBean

Message-Driven Bean Class 消息驱动的Bean类

the requirements of a message-driven bean class: 消息驱动bean类的要求:

 It must not define the finalize method. 

What is the reason for above requirement ? 达到上述要求的原因是什么?

If you look in the EJB spec, you will see that it is a requirement for all types of EJB. 如果您查看EJB规范,就会发现这是所有类型EJB的要求。

http://download.oracle.com/otndocs/jcp/ejb-3.1-pfd-oth-JSpec/ http://download.oracle.com/otndocs/jcp/ejb-3.1-pfd-oth-JSpec/

I can't find a definitive answer but looking on various Java forums over the last 13 years, you can see answers consistently saying that, because the container will decide the life-cycle of the EJB, the finalize may never be called (or called when you don't expect) and it would there be dangerous to use it. 我找不到一个明确的答案,但是在过去的13年中,在各种Java论坛上看到的答案都一致地表明,由于容器将决定EJB的生命周期,因此finalize可能永远不会被调用(或称为当您不期望使用时),使用它会有危险。

https://community.oracle.com/thread/1582366 https://community.oracle.com/thread/1582366

The reason is that the bean lifecycle is managed by a container (either EJB, CDI or different one) so you should use methods annotated with @PreDestroy to do your cleanup when the bean is going to be disposed. 原因是该bean的生命周期是由一个容器(EJB,CDI或其他容器)管理的,因此当要处理该bean时,应使用带有@PreDestroy注释的@PreDestroy进行清理。 Remember that calling of finalize during object disposal is not guaranteed by JVM so you should never use it even in Java SE environment (Java doesn't have concept of destructors like in C++). 请记住,JVM不能保证在对象处置期间调用finalize ,因此即使在Java SE环境中也永远不要使用它(Java没有像C ++这样的析构函数的概念)。

An MDB is not garbage collected unless it fails by number of times configured in the server. 除非按服务器中配置的次数失败,否则MDB不会被垃圾回收。 And so, this method may never be called at all since MDBs are pooled in the MDB pool and just reused as needed. 因此,此方法可能根本不会被调用,因为MDB被存储在MDB池中,并且仅在需要时被重用。 Since finalize method is called by the GC, then it's rational that you should not define it in your MDB since all it's life cycle is managed by the EJB container. 由于finalize方法是由GC调用的,因此不应该在MDB中定义它是合理的,因为它的所有生命周期都由EJB容器管理。 You won't get any exception if you overridden the method since it's already inherited from the Object class, but it's unpredictable when will the code inside it be called. 如果您重写了该方法,则不会有任何异常,因为它已经从Object类继承了,但是何时调用其中的代码是不可预测的。 Also, it will be too late to access any resources in the MDB, since the EJB container would have already done it's cleaning job of closing connections and so forth 此外,访问MDB中的任何资源也为时已晚,因为EJB容器已经完成了清理连接的清理工作,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM