Skip to Content

There is a method finalized defined on Object:

/wp-content/uploads/2016/06/clipboard1_983392.png

In order to test this method, I wrote the following test code:


package basic;
public class finalizeTest {
 private String name;
 public void finalize(){
  System.out.println("finalize called: " + this.name);
  System.out.println("Thread id in finalize: " + Thread.currentThread().getId());
 }
 public finalizeTest(String name){
  this.name = name;
 }
 public static void main(String[] args) {
  Object object = null;
  System.out.println("Thread id: " + Thread.currentThread().getId());
  finalizeTest test = new finalizeTest("Jerry");
  new finalizeTest("Scala");
  System.gc();
 }
}

The code gives the following output:


Thread id: 1
finalize called: Scala
Thread id in finalize: 3

I have learned two points through this test program:

1. the finalize method redefined in my own class is called in a different thread:

/wp-content/uploads/2016/06/clipboard2_983408.png

2. The object instance with name “Scala” is considered by JVM as “no more reference has pointed to it”, so it is decided by JVM to call finalize method redefined on the class when GC method is called explicitly.

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply