• Post Reply Bookmark Topic Watch Topic
  • New Topic

Effective Java Item 7: Avoid Finalizers  RSS feed

 
Ranch Hand
Posts: 33
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everybody,

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.

Thanks in advance,
Mohit
 
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Deleting/destroying an object just means that it will be eligible for garbage collection. The result for you is that the object has been 'deleted' after a GC...it just doesn't exist anymore.
You can achieve this creating and destroying by creating an instance of a class within a method. This way the created object is a local variable and will be 'deleted' automatically at the end of the method (out of scope).
However, you can not 'delete' an object from the heap yourself. Setting an object to null, does not mean that the object don't exist anymore. It is just unreachable at that moment and will be removed by the GC at any undetermined time.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dennis Grimbergen wrote:You can achieve this creating and destroying by creating an instance of a class within a method. This way the created object is a local variable and will be 'deleted' automatically at the end of the method (out of scope).

Note that the Java Language Specification does not specify when exactly objects are destroyed by the garbage collector. An object which is accessible only through a local variable in a method might be deleted at the moment the method returns, but it might also happen at some other, later time (or maybe not even at all, if the JVM exits before the GC has destroyed the object). Because of this, there is no guarantee that a finalizer will always be run.

There is no way in Java to explicitly destroy an object.

In practice you never need to implement finalizers, and they have important disadvantages, as the book says.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!