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){} } }
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.
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.
18 Answers. Save this answer. Show activity on this post. The finalize method is called when an object is about to get garbage collected.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With