finalize method in MessageDrivenBean

安稳与你 提交于 2019-12-24 14:12:32

问题


Message-Driven Bean Class

the requirements of a message-driven bean class:

It must not define the finalize method.

What is the reason for above requirement ?


回答1:


If you look in the EJB spec, you will see that it is a requirement for all types of EJB.

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.

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




回答2:


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. 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++).




回答3:


An MDB is not garbage collected unless it fails by number of times configured in the server. And so, this method may never be called at all since MDBs are pooled in the MDB pool and just reused as needed. 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. 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. 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



来源:https://stackoverflow.com/questions/33774670/finalize-method-in-messagedrivenbean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!