Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: ill defined finalize method to create memory leak

Tags:

java

In java the garbage collect will invoke finalize method on an object x if there's no strong reference pointing to x and x is eligible for garbage collection. What if the finalize method never terminates, would this cause a memory leak?

public class X{
  protected void finalize(){
     while(true){}
  }
}
like image 522
user121196 Avatar asked Jan 24 '13 11:01

user121196


People also ask

What can cause memory leak in Java?

In general, a Java memory leak happens when an application unintentionally (due to logical errors in code) holds on to object references that are no longer required. These unintentional object references prevent the built-in Java garbage collection mechanism from freeing up the memory consumed by these objects.

Why we should not use finalize method in Java?

finalize() methods do not work in chaining like constructors. It means when you call a constructor then constructors of all superclasses will be invoked implicitly. But, in the case of finalize() methods, this is not followed. Ideally, parent class's finalize() should be called explicitly but it does not happen.

When should you use finalize () method in Java?

18 Answers. Save this answer. Show activity on this post. The finalize method is called when an object is about to get garbage collected.


1 Answers

Yes it will, easy to test

public class X {

    protected void finalize() {
        while (true) {
        }
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            new X();
        }
    }
}

after some time I got

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"

when I removed finalize() the test never stopped. Note that it takes a while before JVM goes OOM

BTW it's enough to run this test

public class X {
    byte[] a = new byte[100 * 1000 * 1000];

    protected void finalize() {
        System.out.println();
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            new X();
        }
    }
}

to break GC

Exception in thread "main" 
java.lang.OutOfMemoryError: Java heap space
    at test.X.<init>(X.java:5)
    at test.X.main(X.java:13)

comment out //System.out.println(); and it works non-stop

like image 118
Evgeniy Dorofeev Avatar answered Oct 03 '22 02:10

Evgeniy Dorofeev