AutoCloseable详解

参考资料地址: AutoCloseable详解

用途

利用AutoCloseable的特性可以在关闭资源前做一些事情

1. Java Doc 正文

代表一个对象在close之前可能持有某些资源(文件或socket)。如果对象是在try-with-resources代码块中声明的, AutoCloseable对象的close()方法会被自动执行。这种构造方式保证了最快的资源释放,避免资源耗尽异常。

2. 方法

void close() throws Exception
关闭资源,放弃所有内在的资源。如果对象是在try-with-resources代码块中声明的,那么这个方法会自动被执行

3. 用法

AutoCloseable的实现类,如果对象在try-with-resources代码块中声明的,close方法会自动执行

4. 样例代码

写一段简单的测试代码来验证在try-with-resources代码块中声明AutoCloseable类,jvm会自动调用close方法

4.1 AutoCloseable的实现类

import lombok.Data;
@Data
public class AutoCloseAbleImpl implements AutoCloseable {


    @Override
    public void close() throws IllegalArgumentException {
        this.exit();
        System.out.println("关闭资源");
    }

    public void doSomething(){
        System.out.println("现在资源是开着的");
    }
    private void exit(){
        System.out.println("做一些关闭资源前要做的事情");
    }
}

4.2 测试类

import lombok.Cleanup;

public class AutoCloseAbleExample {

    /**
     * 使用try-with-resources模式声明资源
     *
     * @param args
     */
    public static void main(String[] args) {

        //test1();
        test2();
        //test3();
    }

    /**
     * 对象声明在try-with-resources代码块中,会调用close方法,
     */
    private static void test1() {
        try (AutoCloseAbleImpl test = new AutoCloseAbleImpl()) {
            test.doSomething();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 该写法不会调用close方法
     */
    private static void test2() {
        try  {
            AutoCloseAbleImpl test = new AutoCloseAbleImpl();
            test.doSomething();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 对象声明在try-with-resources代码块中(简写方式),会调用close方法,
     */
    private static void test3() {
        @Cleanup AutoCloseAbleImpl test = new AutoCloseAbleImpl();
        test.doSomething();
    }

}

5. 上班的一天

//老板
public class Boss {
    /**
     * 分配任务
     * @param employee
     */
    void assignTasks(Employee employee){
        System.out.println("boss 分配任务");
        for (int i = 1; i <= 3; i++) {
            employee.addWork("任务"+i);
        }
    }
}
//员工
public class Employee implements AutoCloseable {
    private List<String> works;
    @Override
    public void close() throws Exception {
        getOffWork();
    }
    /**
     * 下班
     */
    private void getOffWork(){
        System.out.println("看看还有那些工作没完成");
        finishWork();
        System.out.println("终于下班了");
    }
    public void addWork(String work){
        if (works==null){
           works=new ArrayList<>();
        }
        works.add(work);
    }
    /**
     * 完成剩余的工作
     */
    private void finishWork() {
        if (works==null||works.isEmpty()){
            return;
        }
        for (String work : works) {
            System.out.println("完成"+work);
        }
    }
}
//测试类
public class ExampleTest {
    @SneakyThrows
    public static void main(String[] args) {
        Boss boss = new Boss();
        @Cleanup Employee employee = new Employee();
        System.out.println("新的一天开始了");
        boss.assignTasks(employee);
        System.out.println("快要下班了");
    }
}

结果

新的一天开始了
boss 分配任务
快要下班了
看看还有那些工作没完成
完成任务1
完成任务2
完成任务3
终于下班了

posted @ 2023-01-19 22:19  进击的小蔡鸟  阅读(234)  评论(0编辑  收藏  举报