EMM
EMM

Reputation: 1812

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.

Upvotes: 2

Views: 1282

Answers (2)

supercat
supercat

Reputation: 81105

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 (i.e. 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.

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117589

Once you make the reference variable refers to null (assuming last reference) and that variable gets out of its scope, then the object is eligible to be garbage-collected at next garbage-collection cycle.

Upvotes: 2

Related Questions