zoukankan      html  css  js  c++  java
  • JDK1.7中关于AutoCloseable接口的使用

      1.查看API文档,找到AutoCloseable相关定义

    public interface AutoCloseable

        该接口是从JDK1.7开始引入,并且该接口中只有一个方法close()

    1 void close() throws Exception // 关闭此资源,放弃任何潜在资源

      2.测试AutoCloseable接口,实现自动关闭处理

      2.1新建接口IMessage继承AutoCloseable接口

    1 interface IMessage extends AutoCloseable {
    2     public void send(); //消息发送
    3 }

       2.2新建NetMessage类实现IMessage接口(注意13行:close()方法抛出异常)

     1 class NetMessage implements IMessage { //实现消息的处理机制
     2     private String msg;
     3 
     4     public NetMessage(String msg) {
     5         this.msg = msg;
     6     }
     7 
     8     public boolean open() { // 获取资源连接
     9         System.out.println("【OPEN】获取资源发送连接资源");
    10         return true;
    11     }
    12 
    13     public void close() throws Exception {
    14         System.out.println("【CLOSE】关闭消息发送通道");
    15     }
    16 
    17     @Override
    18     public void send() {
    19         if (this.open()) {
    20             System.out.println("【**发送消息**】" + this.msg);
    21         }
    22     }
    23 }

      2.3 测试类

    1 try (IMessage message = new NetMessage("Hello world")) {
    2   message.send();
    3 } catch (Exception e) {
    4   e.printStackTrace();
    5 }

       2.4运行结果

    【OPEN】获取资源发送连接资源
    【**发送消息**】Hello world
    【CLOSE】关闭消息发送通道

       3.以FileWriter为例,比较两种不同的操作方式:

      3.1.JDK1.7之前,在finally块中手工关闭资源

     1     public static void writeFile(String str) {
     2         FileWriter fw = null;
     3         try {
     4             fw = new FileWriter("E://test.txt", true);
     5             fw.write(str);
     6         } catch (IOException e) {
     7             e.printStackTrace();
     8         } finally {
     9             if (fw != null) {
    10                 try {
    11                     fw.close();
    12                 } catch (IOException e) {
    13                     e.printStackTrace();
    14                 }
    15             }
    16         }
    17     }

     存在问题:

    • 开发过程中可能会忘记关闭一些资源,导致内存泄漏;
    • 关闭代码的逻辑较冗长,可读性比较差。

       3.2.JDK1.7之后,使用AutoCloseable进行自动关闭

    1     public static void newWriteFile(String str) {
    2         try (FileWriter fw = new FileWriter("", true)) {
    3             fw.write(str);
    4         } catch (IOException e) {
    5             e.printStackTrace();
    6         }
    7     }

      可以通过查看API文档,在AutoCloseable中查看所有已知的实现类;这里以FileWriter为例: 

    • 点击FIleWriter,查看内部实现:
    public class FileWriter extends OutputStreamWriter
    • 点击OutputStreamWriter,继承抽象类Writer:
    public class OutputStreamWriter extends Writer
    • 点击Writer,其中实现了Closeable接口:
    public abstract class Writer implements Appendable, Closeable, Flushable 
    • 点击Closeable接口,查看内部实现,发现该接口继承AutoCloseable接口(该接口只有close()方法):
    public interface Closeable extends AutoCloseable

     总结:

    • AutoCloseable从1.7版本开始引入;
    • AutoCloseable只有一个方法close(),并且抛出异常;
    • 实现AutoCloseable自动关闭资源:

        1.接口继承AutoCloseable接口(或者类实现AutoCloseable接口);

        2.结合异常处理语句:try()...catch()实现自动关闭处理。

       

    其他结论

      1.JDK1.7之前,通常使用 try...catch()捕获异常,在finally部分关闭IO流等,但JDK1.7之后,Java7的编译器和运行环境支持新的try-with-resources语句(ARM块,自动资源管理),写在()里面的对象对应的类实现了自动关闭接口AutoCloseable。

      2.对于实现AutoCloseable接口的类的实例,将其放到try后面(带资源的try语句),在try(){}结束的时候会自动将这些资源关闭(调用close()方法)。

      3.带资源的try语句的3个关键点:

    •   由带资源的try语句管理的资源必须是实现了AutoCloseable接口的类的对象;
    •   在try语句中声明的资源被隐式声明为final;
    •   通过分号分隔每个声明可以管理多个资源。

    文中部分内容和结论依据其它资料进行整理修改,若存在不妥之处,还请留言指正。 

  • 相关阅读:
    用正则表达式简单加密(C#为例)
    新浪微博error:redirect_uri_mismatch的解决方法 [
    UITableView延伸:点击cell关闭键盘,加载不同cell,监听里面的textfeild内容改变
    iossharesdk微信登录出错
    关于IOS项目QQ空间授权提示安装最新版本的QQ的解决方法!
    如何解决 错误code signing is required for product type 'xxxxx' in SDK 'iOS 8.2'
    UITableView加载几种不同的cell
    iOS学习小结(一)
    开源中国+soucetree
    获取本机ip地址
  • 原文地址:https://www.cnblogs.com/moreforests/p/13470297.html
Copyright © 2011-2022 走看看