Java中final、finally、finalize的区别

final: final is a keyword. The variable decleared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden.

finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected.

public class TestMain {
  public static void main(String[] args) {
    try {
      System.out.println("try");
      return;
    } finally {
      // here will be printed
      System.out.println("finally");
    }
  }
}
public class TestMain {
  public static void main(String[] args) {
    try {
      System.out.println("try");
      System.exit(0);
    } finally {
      // here will not be printed
      System.out.println("finally");
    }
  }
}
public class TestMain {
  public static void main(String[] args) {
    try {
      System.out.println("try");
      Runtime.getRuntime().exit(0);
    } finally {
      // here will not be printed
      System.out.println("finally");
    }
  }
}

The only times finally won't be called are:

1. if you call System.exit().

2. another thread interrupts current one (via the interrupt method).

3. if the JVM crashes first.

参考资料:

1. In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

2. Does finally always execute in Java?

本文标题:Java中final、finally、finalize的区别

本文链接:http://yedward.net/?id=369

本文版权归作者所有,欢迎转载,转载请以文字链接的形式注明文章出处。

相关文章