Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and manually executing finalize

If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object?

This would be an approximate example:

MyObject m = new MyObject();

m.finalize();

m = null;

System.gc()

Would the explicit call to finalize() make the JVM's garbage collector not to run the finalize() method on object m?

like image 756
Iker Jimenez Avatar asked Aug 26 '08 18:08

Iker Jimenez


People also ask

Can we call finalize method manually in java?

finalizing! Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.

Why finalize () method should be avoided in java?

“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.” So, in one way we can not guarantee the execution and in another way we the system in danger.

What is finalize () method in java?

Overview. Finalize method in Java is an Object Class method that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the object from memory. Finalize() method is called by default for every object before its deletion.

Can we call finalize explicitly?

So we cannot explicitly call finalize() on any object and even if we do it will only execute when GC happens.


1 Answers

According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it:

private static class Blah
{
  public void finalize() { System.out.println("finalizing!"); }
}

private static void f() throws Throwable
{
   Blah blah = new Blah();
   blah.finalize();
}

public static void main(String[] args) throws Throwable
{
    System.out.println("start");
    f();
    System.gc();
    System.out.println("done");
}

The output is:

start
finalizing!
finalizing!
done

Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.

like image 120
Outlaw Programmer Avatar answered Oct 08 '22 19:10

Outlaw Programmer