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
相关推荐
2的n次方_6 小时前
CANN Ascend C 编程语言深度解析:异构并行架构、显式存储层级与指令级精细化控制机制亓才孓6 小时前
[JDBC]PreparedStatement替代Statement_F_y7 小时前
C++重点知识总结打工的小王7 小时前
Spring Boot(三)Spring Boot整合SpringMVC毕设源码-赖学姐7 小时前
【开题答辩全过程】以 高校体育场馆管理系统为例,包含答辩的问题和答案我真会写代码7 小时前
SSM(指南一)---Maven项目管理从入门到精通|高质量实操指南vx_Biye_Design7 小时前
【关注可免费领取源码】房屋出租系统的设计与实现--毕设附源码40805java干货7 小时前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序_F_y7 小时前
C语言重点知识总结(含KMP详细讲解)DN金猿7 小时前
接口路径正确,请求接口却提示404