JDK1.8源码学习--lang包(AutoCloseable)

前言


月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)

央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)

泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)

月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容

希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!
 

一.AutoCloseable的作用

       1. 直接撸源码英文注释:

/**
 * An object that may hold resources (such as file or socket handles)
 * until it is closed. The {@link #close()} method of an {@code AutoCloseable}
 * object is called automatically when exiting a {@code
 * try}-with-resources block for which the object has been declared in
 * the resource specification header. This construction ensures prompt
 * release, avoiding resource exhaustion exceptions and errors that
 * may otherwise occur.
 *
 * @apiNote
 * <p>It is possible, and in fact common, for a base class to
 * implement AutoCloseable even though not all of its subclasses or
 * instances will hold releasable resources.  For code that must operate
 * in complete generality, or when it is known that the {@code AutoCloseable}
 * instance requires resource release, it is recommended to use {@code
 * try}-with-resources constructions. However, when using facilities such as
 * {@link java.util.stream.Stream} that support both I/O-based and
 * non-I/O-based forms, {@code try}-with-resources blocks are in
 * general unnecessary when using non-I/O-based forms.
 *
 * @author Josh Bloch
 * @since 1.7
 */

        2.从源码注释.我们可以知道:

     1.这个接口是作用于一些掌握某些资源的对象(比如一些文件或者建立连接),而这个接口可以在这些对象 退出之前迅速的释放这些资源,避免出现一些异常和错误

        2.即使一个基类下的部分子类和实例并不持有某些可释放的资源,实现该接口也并不意外,意思就是多实现AutoCloseable也没有什么问题

         3.对于一些需要去释放资源的对象,推荐使用try-catch-resource的形式来释放资源,但是也有一些特殊情形,比如Stream中的Nio 并不是必须的

    通俗的讲,就是这个接口实现了一种新的释放资源的结构方式,之前没有这个接口的时候,我们都需要在finally{}块中去手动释放资源,但是现在只需要在try()中去定义即可,等到try代码块的结束(无论是正常结束,还是异常结束,只要离开该代码块)完成后资源会自动释放掉.

         3.举例说明

package text.lang;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 月央泽
 */
public class AutoCloseableText {

    public static class CustomeObject implements AutoCloseable{
        @Override
        public void close() throws Exception {
            System.out.println("自动关闭了....");
        }
    }



    /**
     * 1.7之前
     */
    public static void releaseBefore(){
        InputStream inputStream = null ;
        try {
            inputStream = new FileInputStream("123");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 1.8及以后
     * 只要实现AutoCloseable接口
     */
    public static void releaseNow(){

        try( CustomeObject customeObject = new CustomeObject()) {
            //当离开当前代码块,资源会被自动释放
            System.out.println("正常结束....");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void releaseNowErro(){

        try( CustomeObject customeObject = new CustomeObject()) {
            //当离开当前代码块,资源会被自动释放
            int i = 10/0;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常了...");
        }

    }

    public static void main(String[] args) {
        //正常演示
        releaseNow();
        System.out.println("============================");
        //异常演示
        releaseNowErro();
    }
}

                演示结果:

        

 可以看到,无论是正常执行,还是异常结束都会自动关闭相关资源(前提是当前对象实现了AutoCloseable接口).

二.AutoCloseable方法

/**
 
     * 1.这个方法就是通过try-with-resource结构来自动管理释放资源

     * 2.这个方法是会抛出异常,但是可以通过更具体的实现类来抛出更具体的异常(为了更方便的排查问题)
     * ,当天也可以选择不抛出异常,如果操作不会失败的话
     *

     * 3,需要实施者注意的是关闭操作可能失败的情况,因此强烈建议在抛出异常之前,
     * 放弃底层的资源并将其标记会关闭.这个方法不太可能被执行多次,因此要确保这些资源被
     * 及时的释放.此外它减少了一些资源包装或被包装时可能出现的问题

     * 4.强烈建议实现者,不要在这个接口抛出InterruptedException异常
     *

     * 5.此异常(InterruptedException)会和线程的中断状态交互,可能会导致运行时不正常的行为出现
     *

     * 6.更一般的说,如果它导致一些异常被压制,AutoCloseable接口就不应该抛出InterruptedException
     * 7.因此,说来说去就是尽量不要抛出InterruptedException,避免不必要的麻烦
     *

     * 8.这个接口的方法和Closeable中的close方法不一样,这个AutoCloseable的方法没有被要求幂等
     * 换句话说,多次调用这个方法可能会出现一些副作用,但是Closeable的close方法多次调用没有影响
     *

     * 9.因此强烈建议,实现者们,让这个方法具有幂等性

     */
    void close() throws Exception;

三.总结

        AutoCloseable接口,让释放资源变得更加智能化.

        说明时候csdn也能让月央泽,更加智能化...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值