桂林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. jq监听

    $(window).resize(function () {//风电月表格自适应高度 var handHeight =$(".tree-handler").height() $(& ...

  2. java课程之团队开发冲刺阶段2.9

    总结昨天进度: 已经完成查询课程信息任务 遇到的困难: 已经全部解决 今天的任务: 修改APP图标 当日总结: manifest中管理着APP的基本信息资料,所以是在manifest文件中修改APP的 ...

  3. 一、SAP中添加一个模块到收藏夹后,显示事务代码

    一.在SAP中,如果添加一个模块到收藏夹,默认是看不到事务代码的,如图: 二.我们在附件->设置中勾选显示技术名称 三.保存之后,就会显示出事务代码,如图所示: 不忘初心,如果您认为这篇文章有价 ...

  4. Learning Combinatorial Embedding Networks for Deep Graph Matching(基于图嵌入的深度图匹配)

    1. 文献信息 题目: Learning Combinatorial Embedding Networks for Deep Graph Matching(基于图嵌入的深度图匹配) 作者:上海交通大学 ...

  5. C 的printf函数

    头文件 #include <stdio.h> printf函数是最常用的格式化输出函数,原型为:int printf(char *format,......); printf函数会根据参数 ...

  6. 备份mysql的批处理命令

    需要工具mysqldump.exe的支持,安装mysql默认是带此工具的 批处理命令 set NOW_TIME_HH=%time:~0,2% if "%NOW_TIME_HH%" ...

  7. 2020/2/1 PHP代码审计之变量覆盖漏洞

    0x00 变量覆盖简介 变量覆盖是指变量未被初始化,我们自定义的参数值可以替换程序原有的变量值. 0x01 漏洞危害 通常结合程序的其他漏洞实现完整的攻击,比如文件上传页面,覆盖掉原来白名单的列表,导 ...

  8. vue form 验证

    vue 验证 <Form :model="formModel" label-position="center" :label-width="90 ...

  9. C++11多线程访问时候的数据保护实例

    #include<iostream> #include<thread> #include<string> #include<vector> #inclu ...

  10. ADO多线程数据库查询

    {ADO查询多线程单元} unit ADOThread; interface uses Classes,StdCtrls,ADODB; type TADOThread = class(TThread) ...