1. 背景
在 Java 开发中,很多资源(数据库连接、ZooKeeper 连接、Redis 客户端、文件流等)都需要手动关闭。如果忘记关闭,会导致 资源泄漏(连接占满、内存泄漏、文件句柄耗尽等)。
为了避免这种问题,Java 提供了两种方式来管理资源关闭:
传统
try-finally(Java 7 之前)
try-with-resources(Java 7+ 引入,推荐 ✅)
2. 传统 try-finally 写法
javaConnection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); // 使用连接 System.out.println("连接成功!"); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); // 手动关闭 } catch (SQLException e) { e.printStackTrace(); } } }特点
必须在
finally中手动关闭资源。代码冗余,容易忘记写。
多个资源时,
finally代码会很长。
3. Java 7+ try-with-resources 写法(推荐)
只要资源类实现了
AutoCloseable或Closeable接口,就能在try中创建,Java 会在执行完try后自动关闭资源。
javatry (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "123456")) { // 使用连接 System.out.println("连接成功!"); } catch (SQLException e) { e.printStackTrace(); } // 这里不需要写 finally,conn 会自动关闭特点
简洁,少写很多
finally。更安全,不会忘记关闭资源。
支持多个资源同时管理:
javatry (InputStream in = new FileInputStream("a.txt"); OutputStream out = new FileOutputStream("b.txt")) { // 同时使用 in 和 out }
4. 常见应用场景
(1)数据库连接
javatry (Connection conn = DriverManager.getConnection(url, user, pass)) { // 执行 SQL }(2)ZooKeeper(Curator)
javaRetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); try (CuratorFramework client = CuratorFrameworkFactory.newClient( "127.0.0.1:2181", 60000, 15000, retryPolicy)) { client.start(); // ZooKeeper 操作 }(3)Redis(Jedis)
javatry (Jedis jedis = new Jedis("localhost", 6379)) { jedis.set("key", "value"); }(4)文件流
javatry (FileInputStream fis = new FileInputStream("a.txt")) { int data; while ((data = fis.read()) != -1) { System.out.print((char) data); } }
5. 总结对比
写法 关闭方式 代码量 出错风险 try-finally 手动关闭 冗余多 容易忘记关闭 try-with-resources 自动关闭(需实现 AutoCloseable)简洁 安全,推荐 ✅
✅ 结论:
如果用的是 Java 7 及以上版本,强烈推荐使用 try-with-resources。
这种写法常用于 数据库、ZooKeeper、Redis、IO 流 等需要关闭的资源管理。
java--写在 try 中的创建连接
你我约定有三2025-09-05 23:40
相关推荐
超级大只老咪16 小时前
数组相邻元素比较的循环条件(Java竞赛考点)小浣熊熊熊熊熊熊熊丶16 小时前
《Effective Java》第25条:限制源文件为单个顶级类毕设源码-钟学长16 小时前
【开题答辩全过程】以 公交管理系统为例,包含答辩的问题和答案啃火龙果的兔子16 小时前
JDK 安装配置星哥说事16 小时前
应用程序监控:Java 与 Web 应用的实践派大鑫wink16 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势xUxIAOrUIII16 小时前
【Spring Boot】控制器Controller方法Dolphin_Home17 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)等....17 小时前
Miniconda使用zfj32117 小时前
go为什么设计成源码依赖,而不是二进制依赖