java--写在 try 中的创建连接

1. 背景

在 Java 开发中,很多资源(数据库连接、ZooKeeper 连接、Redis 客户端、文件流等)都需要手动关闭。如果忘记关闭,会导致 资源泄漏(连接占满、内存泄漏、文件句柄耗尽等)。

为了避免这种问题,Java 提供了两种方式来管理资源关闭:

  • 传统 try-finally(Java 7 之前)

  • try-with-resources(Java 7+ 引入,推荐 ✅)


2. 传统 try-finally 写法

java 复制代码
Connection 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 写法(推荐)

只要资源类实现了 AutoCloseableCloseable 接口,就能在 try 中创建,Java 会在执行完 try 后自动关闭资源。

java 复制代码
try (Connection conn = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/test", "root", "123456")) {
    // 使用连接
    System.out.println("连接成功!");
} catch (SQLException e) {
    e.printStackTrace();
}
// 这里不需要写 finally,conn 会自动关闭

特点

  • 简洁,少写很多 finally

  • 更安全,不会忘记关闭资源。

  • 支持多个资源同时管理:

    java 复制代码
    try (InputStream in = new FileInputStream("a.txt");
         OutputStream out = new FileOutputStream("b.txt")) {
        // 同时使用 in 和 out
    }

4. 常见应用场景

(1)数据库连接

java 复制代码
try (Connection conn = DriverManager.getConnection(url, user, pass)) {
    // 执行 SQL
}

(2)ZooKeeper(Curator)

java 复制代码
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
try (CuratorFramework client = CuratorFrameworkFactory.newClient(
        "127.0.0.1:2181", 60000, 15000, retryPolicy)) {
    client.start();
    // ZooKeeper 操作
}

(3)Redis(Jedis)

java 复制代码
try (Jedis jedis = new Jedis("localhost", 6379)) {
    jedis.set("key", "value");
}

(4)文件流

java 复制代码
try (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 流 等需要关闭的资源管理。

相关推荐
小陈工6 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
H Journey6 小时前
C++之 CMake、CMakeLists.txt、Makefile
开发语言·c++·makefile·cmake
一定要AK10 小时前
Spring 入门核心笔记
java·笔记·spring
A__tao10 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
KevinCyao10 小时前
java视频短信接口怎么调用?SpringBoot集成视频短信及回调处理Demo
java·spring boot·音视频
lly20240610 小时前
C 标准库 - `<stdio.h>`
开发语言
沫璃染墨10 小时前
C++ string 从入门到精通:构造、迭代器、容量接口全解析
c语言·开发语言·c++
jwn99910 小时前
Laravel6.x核心特性全解析
开发语言·php·laravel
迷藏49410 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
功德+n11 小时前
Linux下安装与配置Docker完整详细步骤
linux·运维·服务器·开发语言·docker·centos