Monday, 18 March 2013

To kill a GC

This is actually an answer for a recent patch written at work. So what happens if you have an object, which overrides the finallize method and in that it needs to wait for a while, e.g. to wait for a thread to join (database transaction to finish, IO operation, and so on).

This is an example code, it does not wait for a thread for 20 seconds, it only sleeps for 1, but anyway it gives a little work for the GC.

import java.util.Date;

public class Main {

 final int nr;
 final byte[] justsomememory;

 public Main(int nr) {
  this.nr = nr;
  justsomememory = new byte[1024 * 1024];
 }

 public static void main(String[] args) throws Exception {
  for (int i = 0; i < 20000; i++) {
   Main main = new Main(i);
    Thread.sleep(10);
  }
 }

 @Override
 protected void finalize() throws Throwable {
  Thread.sleep(1000);
 }

}


Let's use the jconsole to look under the hood of the VM.

This is a healthy memory usage.
This is what you see if you have any blocking operations in finaly()
I think this is visual enough. So in general, I agree with those who try to avoid having a finallize method in their code. And really why should you have one?

No comments:

Post a Comment