在 java 中,处理需要释放资源的对象时,应优先使用 try-with-resources 语句,仅在无法实现 autocloseable 接口的遗留代码或特定场景下才考虑 finalize。try-with-resources 通过自动调用 close() 方法确保资源被及时、确定性地释放,而 finalize 方法由垃圾回收器在不可预测的时间调用,可能导致资源泄漏和性能问题。

try-with-resources 如何确保资源安全释放
try-with-resources 要求资源类实现 AutoCloseable 接口,并在 try 块结束时自动调用 close() 方法。这种方式保证了即使发生异常,资源也会被正确关闭,避免了传统 try-catch-finally 代码的繁琐和潜在错误。

import java.io.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
// 模拟一个需要关闭的资源
Resource resource = new Resource();
// 使用 try-with-resources 自动管理资源
try (resource) {
System.out.println("使用资源: " + resource.getData());
// 模拟业务逻辑
if (Math.random() > 0.5) {
throw new RuntimeException("模拟异常");
}
} catch (Exception e) {
System.out.println("捕获异常: " + e.getMessage());
}
// 资源已自动关闭
System.out.println("资源是否已关闭: " + resource.isClosed());
}
}
class Resource implements AutoCloseable {
private boolean closed = false;
private String data = "重要数据";
public String getData() {
if (closed) {
throw new IllegalStateException("资源已关闭");
}
return data;
}
@Override
public void close() throws Exception {
closed = true;
System.out.println("资源已关闭");
}
public boolean isClosed() {
return closed;
}
}
预期结果:无论是否抛出异常,Resource 对象的 close() 方法都会被调用,输出“资源已关闭”,并且 isClosed() 返回 true。
finalize 方法的局限性和风险
finalize 方法是 Object 类的受保护方法,由垃圾回收器在对象被回收前调用。然而,finalize 的执行时间不确定,可能导致资源长时间未被释放,引发内存泄漏或系统不稳定。此外,finalize 方法已被标记为废弃,Java 9 起推荐使用 Cleaner 替代。

import java.lang.ref.Cleaner;
public class FinalizeExample {
private static final Cleaner cleaner = Cleaner.create();
private boolean cleaned = false;
public FinalizeExample() {
// 注册清理动作
cleaner.register(this, new CleanupTask());
}
// 模拟资源清理任务
private static class CleanupTask implements Runnable {
@Override
public void run() {
System.out.println("执行清理任务");
// 实际清理逻辑
}
}
public static void main(String[] args) {
FinalizeExample example = new FinalizeExample();
// 模拟业务逻辑
System.out.println("业务逻辑执行完毕");
// 不再引用 example,等待垃圾回收
example = null;
// 建议手动触发垃圾回收(仅用于测试)
System.gc();
try {
Thread.sleep(1000); // 等待清理
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
预期结果:CleanupTask 的 run() 方法会被调用,但执行时间不确定,可能延迟较久。相比之下,try-with-resources 能立即释放资源。
try-with-resources 中多个资源的管理策略
当需要同时管理多个资源时,try-with-resources 支持在同一个 try 语句中声明多个资源,它们会按声明顺序的逆序关闭。这种机制简化了多资源管理的代码结构,避免了嵌套 try-catch 的复杂性。
import java.io.*;
public class MultipleResourcesExample {
public static void main(String[] args) {
Resource resource1 = new Resource("资源1");
Resource resource2 = new Resource("资源2");
// 同时管理多个资源
try (resource1; resource2) {
System.out.println("使用资源1: " + resource1.getData());
System.out.println("使用资源2: " + resource2.getData());
} catch (Exception e) {
System.out.println("捕获异常: " + e.getMessage());
}
// 验证关闭顺序
System.out.println("资源1是否已关闭: " + resource1.isClosed());
System.out.println("资源2是否已关闭: " + resource2.isClosed());
}
}
预期结果:资源2先关闭,然后资源1关闭,两者均被正确释放,isClosed() 均返回 true。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











