Java - 如果用户意外关闭程序,try-with-resources 会调用 .close() 吗?

Java - Will try-with-resources call .close() if the user closes the program unexpectedly?

我正在为我正在开发的程序编写一些服务器代码,我正在使用 try-with-resource 语句来关闭套接字。

try (
            ServerSocket serverSocket = new ServerSocket(port);
            Socket clientSocket = serverSocket.accept();

            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        ) {


        out.println("This is the server! Hooray! :D");


    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }

问题是,如果用户决定在 try 块完成之前关闭程序怎么办? .close() 方法会被调用吗?

这是在 oracle 的网站上:it will be closed regardless of whether the try statement completes normally or abruptly 但我不确定这是否包括用户在尝试完成之前关闭程序还是程序崩溃。

谢谢。

Yes/no,

"The try-with-resources statement ensures that each resource is closed at the end of the statement"

可以在 Oracle

找到

只要把它想象成一个 finally 块。 finally 总是会被执行。

"Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues."

这可以在 Oracle

找到

不,不会。

Runtime.addShutdownHook 如果您需要它们会提供更多保证,但仍然不是 100%,因为如果 JVM crashes/someone 从外部强行终止 JVM,它不会被调用。

最好的解决方案是让包装进程启动您的 Java 应用程序,监视它并在监视进程终止时执行您需要的操作。

如果我没有正确理解你的问题,我认为它不会关闭。 try 块必须优雅地完成或捕获一些异常才能关闭资源。所以它应该是一个检查异常。我相信如果您在尝试使用资源时遇到 RuntimeException,那么该资源将被关闭。但它不会关闭线程资源或 JVM 因 OOM 等问题而崩溃。