java 7 引入的 try-with-resources 语句通过让资源类实现 autocloseable 接口,在代码块结束时自动调用 close() 方法来释放资源。你只需将需要管理的资源定义在 try 后的括号中,jvm 就会保证即使发生异常也会执行关闭操作,从而避免资源泄漏。

哪些类支持自动关闭机制
所有实现了 java.lang.AutoCloseable 接口的类都可以被 try-with-resources 管理。这包括常见的 InputStream、OutputStream、Reader、Writer 以及 JDBC 的 Connection、Statement 等。只要类实现了该接口并定义了 close() 方法,就可以放入括号中进行自动管理。

import java.io.*;
public class AutoCloseDemo {
public static void main(String[] args) {
// 定义一个实现 AutoCloseable 的资源
MyResource resource = new MyResource("test");
// try-with-resources 自动管理
try (MyResource res = resource) {
System.out.println("使用资源: " + res.getData());
} catch (Exception e) {
System.err.println("发生错误: " + e.getMessage());
}
// 离开 try 块后,res.close() 自动被调用
System.out.println("资源已关闭: " + resource.isClosed());
}
}
class MyResource implements AutoCloseable {
private String data;
private boolean closed = false;
public MyResource(String data) {
this.data = data;
}
public String getData() {
if (closed) throw new IllegalStateException("Resource is closed");
return data;
}
@Override
public void close() throws Exception {
this.closed = true;
System.out.println("MyResource closed.");
}
public boolean isClosed() {
return closed;
}
}
运行上述代码,输出顺序为:先打印“使用资源: test”,然后打印“MyResource closed.”,最后打印“资源已关闭: true”。这证明了 close() 是在 try 块结束后自动执行的。
多个资源如何声明与管理
当需要同时管理多个资源时,可以在 try 括号内用分号 ; 分隔它们。这些资源会按照声明的逆序(从最后一个到第一个)依次关闭。如果创建或关闭过程中发生异常,close() 抛出的异常会被抑制,而不会掩盖原始异常。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

import java.io.*;
public class MultiResourceDemo {
public static void main(String[] args) {
try (
InputStream in = new FileInputStream("input.txt");
OutputStream out = new FileOutputStream("output.txt")
) {
// 模拟读取和写入
byte[] buffer = new byte[10];
int read = in.read(buffer);
if (read > 0) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
}
}
}
在这个例子中,如果 out.close() 抛出异常,它会被添加到原始 in.read() 或 out.write() 引发的异常的 suppressed exceptions 列表中,确保主异常能被正确捕获和处理。
try-with-resources 中的异常处理细节
如果在 try 块内部和 close() 方法中都发生了异常,try-with-resources 会将 close() 抛出的异常作为“抑制异常”附加到主异常上。你可以通过 getSuppressed() 方法获取这些被抑制的异常。这种机制确保了资源的关闭不会因为主逻辑的异常而被忽略,同时也保留了主要的错误信息。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










