Skip to content

Instantly share code, notes, and snippets.

@caoxudong
Last active August 29, 2015 14:05
Show Gist options
  • Save caoxudong/50386bbfa0b92f0569ef to your computer and use it in GitHub Desktop.
Save caoxudong/50386bbfa0b92f0569ef to your computer and use it in GitHub Desktop.
bad finalize method
package test.jvm.gc;
public class TestFinalizeMethod {
public static T t;
public static void main(String[] args) throws InterruptedException {
run();
System.out.println(t==null?1:2);
System.gc();
Thread.sleep(3000);
System.out.println(t==null?1:2);
t = null;
System.out.println(t==null?1:2);
System.gc();
Thread.sleep(3000);
System.out.println(t==null?1:2);
}
public static void run() {
T t = new T();
}
public static class T {
int i = 1;
@Override
protected void finalize() throws Throwable {
TestFinalizeMethod.t = this; // save itself
System.err.println(new RuntimeException("haha")); // only call it once
throw new RuntimeException("haha"); //ignore exception
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment