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
相关推荐
多加点辣也没关系4 小时前
JavaScript|第41章:性能优化实战Resean02234 小时前
架构设计系列(十六):DDD 与代码架构学长毕设5 小时前
基于SpringBoot 车辆租赁系统平台-附源码码途行者5 小时前
每天10分钟学Go:第22课 自定义错误23图5 小时前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]feixing_fx6 小时前
解构与展开:可读性和性能的取舍小飞在努力6 小时前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装Flynt7 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天饮水桶_T10 小时前
C++ stack & queue复习笔记她的男孩10 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配