How to address the “Do not override the Object.finalize() method” issue

余生颓废 提交于 2019-12-11 12:49:44

问题


Recently I figure out one tool [SonarQube] who helps me to find out the potential threats into code, I have addressed all issues reported by the tool.

But it also gives me a potential threats issue for "protected void finalize()" method which is been override by me, tool displaying me a message "Do not override the Object.finalize() method".

Can anybody please help me how to address this issue, the overrided method also include some business logic.


回答1:


Never. Never! Never put any business logic in finalize(). The only case to override finalize() is when your object allocates some resources, that you forget to free. In that case your finalize() could check is resources still allocated, force them to free, and warn about it in log, or something like that. But in any normal circumstances you do not need to override it. Also, you are not guaranteed, in exactly moment finalize will be invoked. So, you may have unfinalized object remains in the heap until end of the world, or, vice versa, your object could be finalized as soon as reference is lost. In additional, it is not guarantee, in which order objects will be finalized. Whatever your business logic contains, I suppose, that is not what you want.

UPD Also: it is not guaranteed that finalize() will (in most cases it is guaranteed that not) be executed in the same thread as your application, so, having unsynchronized code there could make unpredictable results, synchronized code, also large business logic could slow down an execution of the GC-thread, and therefore slow down entire application.

Instead of overriding finalize(), implement some explicit methods (e.g. close(), or done()), which you will explicitly call when done with this object. Also, when developing under limited-resource devices, it is good practice to reuse objects by multiple calling init/done methods, which allows to reuse internal structure, without unnecessary garbage collection.

So, in conclusion, your helping tool said that right: when overriding finalize() - you are doing something wrong.



来源:https://stackoverflow.com/questions/31183341/how-to-address-the-do-not-override-the-object-finalize-method-issue

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