美文网首页
使用 try-with-resources 关闭资源

使用 try-with-resources 关闭资源

作者: MrDcheng | 来源:发表于2020-02-12 10:23 被阅读0次

JDK7 引入了 try-with-resources,为资源关闭提供了更为方便简洁的方法。以一段简单的 BIO 服务端代码为例,使用传统方式关闭资源:

public static void main(String[] args) {
    ServerSocket serverSocket = null;
    Socket socket = null;
    InputStream inputStream = null;
    try {
        serverSocket = new ServerSocket(3000);
        while (true) {
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();

            byte[] bytes = new byte[5];
            int count = inputStream.read(bytes);
            while (count != -1) {
                for (int index = 0; index < count; index++) {
                    System.out.print((char) bytes[index]);
                }
                count = inputStream.read(bytes);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            serverSocket.close();
            socket.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

可见,为确保资源正确关闭,需要在 finall 中再嵌入 try,打开的资源越多,嵌套也越多,最终可能会出现关闭资源的代码比业务代码还要多的情况。另外,传统方式还存在异常屏蔽的问题。在上例故意制造一个错误,将监听端口号改为 -1,运行服务端时提示如下:

Exception in thread "main" java.lang.NullPointerException
    at com.example.TraditionalTry.main(TraditionalTry.java:32)

该异常指出 finally 块的 serverSocket.close(); 发出空指针异常,并没有指出问题真正所在代码行,即 serverSocket = new ServerSocket(-1);,不利于问题的定位和排查。

为解决上述问题,使用 try-with-resources 改写上例,不仅使代码简洁清晰,而且不会出现异常屏蔽的情况,能够准确指示错误所在:

public static void main(String[] args) throws Exception {
    try (ServerSocket serverSocket = new ServerSocket(3000)) {
        while (true) {
            try (Socket socket = serverSocket.accept()) {
                try (InputStream inputStream = socket.getInputStream()) {

                    byte[] bytes = new byte[5];
                    int count = inputStream.read(bytes);
                    while (count != -1) {
                        for (int index = 0; index < count; index++) {
                            System.out.print((char) bytes[index]);
                        }
                        count = inputStream.read(bytes);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

为进一步验证上述写法,创建两个实现 AutoCloseable 接口的简单资源类。覆盖后的 close() 方法,在提示关闭信息后均发出异常;Outer 类额外有一个提示信息后也会发出异常的 show() 方法:

注:能够使用 try-with-resources 关闭资源的类,必须实现 AutoCloseable 接口。

class Outer implements AutoCloseable {

    public void show() {
        System.out.println("show is running!");
        throw new RuntimeException("Outer show Exception!");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Outer close!");
        throw new RuntimeException("Outer close Exception!");
    }
}

class Inner implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("Inner close!");
        throw new RuntimeException("Inner close Exception!");
    }
}

调用:

public static void main(String[] args) {
    try (Outer outer = new Outer()) {
        try (Inner inner = new Inner()) {
            System.out.println("other code...");
            outer.show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

输出如下。可见资源都已经关闭,被屏蔽的异常也已经显示出来:

other code...
show is running!
Inner close!
Outer close!
java.lang.RuntimeException: Outer show Exception!
    at com.example.Outer.show(TestTryResources.java:20)
    at com.example.TestTryResources.main(TestTryResources.java:8)
    Suppressed: java.lang.RuntimeException: Inner close Exception!
        at com.example.Inner.close(TestTryResources.java:35)
        at com.example.TestTryResources.main(TestTryResources.java:6)
    Suppressed: java.lang.RuntimeException: Outer close Exception!
        at com.example.Outer.close(TestTryResources.java:26)
        at com.example.TestTryResources.main(TestTryResources.java:5)

关于 try-with-resources 的底层实现原理,可以看看编译后的 class 文件:

public static void main(String[] args) {
        try {
            Outer outer = new Outer();

            try {
                Inner inner = new Inner();

                try {
                    System.out.println("other code...");
                    outer.show();
                } catch (Throwable var7) {
                    try {
                        inner.close();
                    } catch (Throwable var6) {
                        var7.addSuppressed(var6);
                    }

                    throw var7;
                }

                inner.close();
            } catch (Throwable var8) {
                try {
                    outer.close();
                } catch (Throwable var5) {
                    var8.addSuppressed(var5);
                }

                throw var8;
            }

            outer.close();
        } catch (Exception var9) {
            var9.printStackTrace();
        }

    }

和传统关闭资源操作的实现原理一样,编译器生成了 finally 代码块,并在其中调用了 close 方法,除此之外,还多调用了一个 addSuppressed 方法来处理异常屏蔽。

相关文章

网友评论

      本文标题:使用 try-with-resources 关闭资源

      本文链接:https://www.haomeiwen.com/subject/sjuqfhtx.html