桂林SEO:我们知道,在 Java 编程过程中,如果打开了外部资源(文件、数据库连接、网络连接等、redis),我们必须在这些外部资源使用完毕后,手动关闭它们。

因为外部资源不由 JVM 管理,无法享用 JVM 的垃圾回收机制,如果我们不在编程时确保在正确的时机关闭外部资源,就会导致外部资源泄露,紧接着就会出现文件被异常占用,数据库连接过多导致连接池溢出**等诸多很严重的问题。

JDK7 之前的资源关闭方式

/**
* jdk7以前关闭流的方式
* */
public class CloseResourceBefore7 {
private static final String FileName = "file.txt"; public static void main(String[] args) throws IOException {
FileInputStream inputStream = null; try {
inputStream = new FileInputStream(FileName);
char c1 = (char) inputStream.read();
System.out.println("c1=" + c1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}

JDK7 之后用 try-with-resource 语法关闭

在 JDK7 以前,Java 没有自动关闭外部资源的语法特性,直到 JDK7 中新增了try-with-resource 语法,才实现了这一功能。

try-with-resource Resource 的定义:所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。

1. 一个例子

一个实现了 java.lang.AutoCloseable 接口的 Resource 类:

/**
* 资源类
* */
public class Resource implements AutoCloseable {
public void sayHello() {
System.out.println("hello");
} @Override
public void close() throws Exception {
System.out.println("Resource is closed");
}
}

测试类 CloseResourceIn7.java

/**
* jdk7及以后关闭流的方式
* */
public class CloseResourceIn7 {
public static void main(String[] args) {
try(Resource resource = new Resource()) {
resource.sayHello();
} catch (Exception e) {
e.printStackTrace();
}
}
}

打印结果:

hello
Resource is closed

当存在多个打开资源的时候: 资源二 Resource2.java

/**
* 资源2
* */
public class Resource2 implements AutoCloseable {
public void sayhello() {
System.out.println("Resource say hello");
} @Override
public void close() throws Exception {
System.out.println("Resource2 is closed");
}
}

测试类 CloseResourceIn7.java

/**
* jdk7及以后关闭流的方式
* */
public class CloseResourceIn7 {
public static void main(String[] args) {
try(Resource resource = new Resource(); Resource2 resource2 = new Resource2()) {
resource.sayHello();
resource2.sayhello();
} catch (Exception e) {
e.printStackTrace();
}
}
}

结果:

hello
hello2
Resource2 is closed
Resource is closed

注意:打开多个资源的时候,关闭顺序是倒叙的

原理

查看编译的 class 文件 CloseResourceIn7.class

public class CloseResourceIn7 {
public CloseResourceIn7() {
} public static void main(String[] args) {
try {
Resource resource = new Resource();
Throwable var2 = null;
try {
resource.sayHello();
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (resource != null) {
if (var2 != null) {
try {
resource.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
}
} else {
resource.close();
}
}
}
} catch (Exception var14) {
var14.printStackTrace();
}
}
}

可以发现编译以后生成了 try-catch-finally 语句块 finally 中的 var2.addSuppressed(var11),这么做是为了处理异常屏蔽的。

我们将代码修改一下 资源 Resource.java,让两个方法里都抛出异常

/**
* 资源类
* */
public class Resource implements AutoCloseable {
public void sayHello() throws Exception {
throw new Exception("Resource throw Exception");
} @Override
public void close() throws Exception {
throw new Exception("Close method throw Exception");
}
}

测试类 CloseResourceBefore7.java

/**
* jdk7以前关闭流的方式
* */
public class CloseResourceBefore7 { public static void main(String[] args) {
try {
errorTest();
} catch (Exception e) {
e.printStackTrace();
}
} private static void errorTest() throws Exception {
Resource resource = null;
try {
resource = new Resource();
resource.sayHello();
} finally {
if (resource != null) {
resource.close();
}
}
}
}

打印结果:

java.lang.Exception: Close method throw Exception
at com.shuwen.Resource.close(Resource.java:15)
at com.shuwen.CloseResourceIn7.errorTest(CloseResourceIn7.java:27)
at com.shuwen.CloseResourceIn7.main(CloseResourceIn7.java:12)

只打印了最后出现的关闭异常【异常屏蔽】这样会给开发人员排查错误带来一定的困难 我们换成 try-with-resource 方法实现CloseResourceIn7.java

/**
* jdk7及以后关闭流的方式
* */
public class CloseResourceIn7 { public static void main(String[] args) {
try {
errorTest();
} catch (Exception e) {
e.printStackTrace();
}
} private static void errorTest() throws Exception {
try(Resource resource = new Resource()) {
resource.sayHello();
} }
}

打印信息:

java.lang.Exception: Resource throw Exception
at com.shuwen.Resource.sayHello(Resource.java:10)
at com.shuwen.CloseResourceIn7.errorTest(CloseResourceIn7.java:20)
at com.shuwen.CloseResourceIn7.main(CloseResourceIn7.java:12)
Suppressed: java.lang.Exception: Close method throw Exception
at com.shuwen.Resource.close(Resource.java:15)
at com.shuwen.CloseResourceIn7.errorTest(CloseResourceIn7.java:21)
... 1 more

可以发现,异常信息中多了一个 Suppressed 的提示,告诉我们这个异常其实由两个异常组成,Close method throw Exception这个异常是被 Suppressed【屏蔽】的异常。

应用:在 Jedis 中的使用

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; public class JedisTest { public static void main(String[] args) {
JedisPool pool = new JedisPool();
try (Jedis jedis = pool.getResource()) { // 用完自动 close
doSomething(jedis);
}
} private static void doSomething(Jedis jedis) {
// code it here
}
}

这样 Jedis 对象肯定会归还给连接池 (死循环除外),避免应用程序卡死的惨剧发生。

使用 try-with-resources 优雅关闭资源的更多相关文章

  1. Effective java 系列之更优雅的关闭资源-try-with-resources

    背景: 在Java编程过程中,如果打开了外部资源(文件.数据库连接.网络连接等),我们必须在这些外部资源使用完毕后,手动关闭它们.因为外部资源不由JVM管理,无法享用JVM的垃圾回收机制,如果我们不在 ...

  2. 更优雅地关闭资源 - try-with-resource及其异常抑制

    原文:https://www.cnblogs.com/itZhy/p/7636615.html 一.背景 我们知道,在Java编程过程中,如果打开了外部资源(文件.数据库连接.网络连接等),我们必须在 ...

  3. Java进阶知识点:更优雅地关闭资源 - try-with-resource

    一.背景 我们知道,在Java编程过程中,如果打开了外部资源(文件.数据库连接.网络连接等),我们必须在这些外部资源使用完毕后,手动关闭它们.因为外部资源不由JVM管理,无法享用JVM的垃圾回收机制, ...

  4. Java进阶知识点3:更优雅地关闭资源 - try-with-resource及其异常抑制

    一.背景 我们知道,在Java编程过程中,如果打开了外部资源(文件.数据库连接.网络连接等),我们必须在这些外部资源使用完毕后,手动关闭它们.因为外部资源不由JVM管理,无法享用JVM的垃圾回收机制, ...

  5. 更优雅地关闭资源 - try-with-resource及其异常抑制--转载

    原文地址:https://www.cnblogs.com/itZhy/p/7636615.html 一.背景 我们知道,在Java编程过程中,如果打开了外部资源(文件.数据库连接.网络连接等),我们必 ...

  6. C++中没有finally,那么应该在如何关闭资源

    这是一篇有趣的帖子 原文链接: http://bbs.csdn.net/topics/90070457 楼主: C++中没有finally,那么应该在哪里关闭资源? C++的try{}catch(){ ...

  7. C++中没有finally,那么应该在哪里关闭资源?

    这是一篇有趣的帖子 原文链接: http://bbs.csdn.net/topics/90070457 楼主: C++中没有finally,那么应该在哪里关闭资源? C++的try{}catch(){ ...

  8. Socket编程中的强制关闭与优雅关闭及相关socket选项

    以下描述主要是针对windows平台下的TCP socket而言. 首先需要区分一下关闭socket和关闭TCP连接的区别,关闭TCP连接是指TCP协议层的东西,就是两个TCP端之间交换了一些协议包( ...

  9. 文件的读取与保存(try-with-resource优雅关闭)

    借鉴:https://www.cnblogs.com/itZhy/p/7636615.html 一.背景 在Java编程过程中,如果打开了外部资源(文件.数据库连接.网络连接等),我们必须在这些外部资 ...

随机推荐

  1. struts2模型驱动传值问题

    控制台错误提示: 2020-01-08 18:34:40,292 [http-nio-8080-exec-3] [org.apache.struts2.dispatcher.Dispatcher]-[ ...

  2. JVM探秘:jinfo查看JVM运行时参数

    本系列笔记主要基于<深入理解Java虚拟机:JVM高级特性与最佳实践 第2版>,是这本书的读书笔记. 如何查看JVM运行时参数,对于线上JVM调优是很关键的,因为只有知道了当前使用的JVM ...

  3. [题解] CF438E The Child and Binary Tree

    CF438E The Child and Binary Tree Description 给一个大小为\(n\)的序列\(C\),保证\(C\)中每个元素各不相同,现在你要统计点权全在\(C\)中,且 ...

  4. Maven - web 实例

    版权所有,未经授权,禁止转载 章节 Maven – 简介 Maven – 工作原理 Maven – Repository(存储库) Maven – pom.xml 文件 Maven – 依赖管理 Ma ...

  5. MessageBox.Show的使用

    MessageBox.Show("内容","标题") // 摘要:// 使用指定的帮助文件.HelpNavigator 和帮助主题显示一个具有指定文本.标题.按 ...

  6. VScode 修改中文字体

    打开vscode ctrl+,打开设置 找到font,第一个是首选的英文字体,第二个是中文字体.

  7. python 流行库、库的基本用法

    进入github,输入python 点击see topic 进入python流行的库  链接 https://github.com/topics/python 1.QuantLib 金融衍生品数据库 ...

  8. String StringBuffer和StringBuilder的区别和联系

    1:String,StringBuffer和StringBuilder概念 1.1:String String中使用字符串数组来存储字符串,但是是fianl来修饰的,所以String的内容不可改变. ...

  9. Python 重新加载模块

    每个Python文件中的import modulename只被加载一遍,如果在运行过程中,这个Module被更改了,即使在在interpretor中运行import 语句也没用. 可以使用import ...

  10. JavaScript学习总结(一)

    概述 前端三剑客,html.css.js. 这三种语言基本是前端开发必备的东西,那么你知道这三种语言分别负责的功能是什么吗? html:负责了一个页面的结构 css:负责页面的样式 JavaScrip ...