简体   繁体   中英

Effective Java Item 7: Avoid Finalizers

In this amazing book the author Josh Bloch mentions:

"Oh, and one more thing: there is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns. In other words, it is about 430 times slower to create and destroy objects with finalizers."

Is there a way we can delete and object in java?
I thought we can simply let the objects fall out of scope or reset them to null.
I intend to experiment this on my machine , seems like a fun idea but I am not sure how to delete and object.

一旦您使引用变量引用了null (假设最后一个引用),并且该变量超出了其范围,则该对象可以在下一个垃圾回收周期进行垃圾回收。

An object will cease to exist when there are no longer any strong rooted references to it; in most cases that's exactly what should happen. In some cases, however, an object will ask an outside entity to do something on its behalf, possibly to the detriment of other entities, in exchange for a promise to let that other entity know when its services are no longer required. For example, a "File" object might ask the OS for exclusive access to a file; until the OS is told that such access is no longer required, it will block everyone else's ability to use that file.

If an object which had made such a promise were abandoned and simply ceased to exist, the outside entity would keep on doing whatever it had been asked to do, to the detriment of everyone else, even though its actions were no longer of any benefit to anyone. To avoid this situation, Java allows objects to request notification when the GC notices that they seem to have been abandoned. Such notifications will be given (ie Finalize will be called on such objects) before the objects cease to exist, but there's no real guarantee of timeliness beyond that. An object which is finalized can then notify any and all entities acting on its behalf that they should stop doing so.

The creators of Java may have expected finalizers to be the primary mechanism by which objects could notify outside entities that their services are no longer required, but finalization really doesn't work very well. Other mechanisms such as AutoCloseable or PhantomReference are better in many cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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