桂林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. BZOJ:1878: [SDOI2009]HH的项链

    题解:解法一:莫队 解法二:按区间左端点排序,让区间内最左边的贝壳对答案产生贡献,树状数组维护,转移对答案产生贡献的贝壳位置 #include<iostream> #include< ...

  2. 量化投资_Multicharts数组操作函数_zeros()设定数组元素为0(自定义)

    1. 函数的用法类似于Python的zeros函数,给定数组尺寸,让数组的元素归零 //zeros:根据设定的尺寸长度,让一维数组的元素全部归零 inputs: arr[MaxSize]( numer ...

  3. 吴裕雄--天生自然TensorFlow2教程:张量排序

    import tensorflow as tf a = tf.random.shuffle(tf.range(5)) a tf.sort(a, direction='DESCENDING') # 返回 ...

  4. 什么是控制反转IOC

    1.IOC 是什么 IOC- Inversion of Control , 即“控制反转” ,不是一个技术,而是一个设计思想,在java 开发中,IOC意味着将你设计好的Java 对象交个容器控制,而 ...

  5. C++保存数据到CSV文件

    主要是今天工作的时候需要把一些数据保存到本地,因为是一些预测值和标签的对比,还有预测值的概率,所以想到用CSV文件来保存,大概查了一下,还是比较简单的,所以记录一下. 首先要说明的是CSV文件有点类似 ...

  6. [Qt5] QSlider设置步长

    这是一个小问题,就是QSlider是一个滑动条控件,既然是个滑动条控件,就会想要用鼠标滚轮或者鼠标去移动它来实现某些功能,但是呢,我能说这个控件的一个属性函数设置也是比较奇怪的,它设置步长的函数有 s ...

  7. HashMap实现原理(jdk1.7),源码分析

    HashMap实现原理(jdk1.7),源码分析 ​ HashMap是一个用来存储Key-Value键值对的集合,每一个键值对都是一个Entry对象,这些Entry被以某种方式分散在一个数组中,这个数 ...

  8. JavaScript 之 Function

    JavaScript function 语句定义和用法: function 语句用于声明一个函数. 函数声明后,我们可以在需要的时候调用. 在 JavaScript 中,函数是对象,函数也有属性和方法 ...

  9. 65)STL中string的知识

    1)代码展示: string是一个类,只不过封装了 char*  而且还封装了  很多的字符串操作函数 2)string类的初始化: string的构造函数 ²  默认构造函数: string();  ...

  10. 63)对于STL基本概念东西 自己百度(没有整理)

    基础知识 看  C++进阶课程讲义的那个word文档