4

I'm working on some server code for a program I'm developing and I'm using try-with-resource statements to close the sockets.

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);
    }

The problem is, what if the user decides to close the program before the try block finishes? Will the .close() methods be called?

This is on oracle's website:it will be closed regardless of whether the try statement completes normally or abruptly But I'm not sure if that includes if the user just closes the program before the try finishes or just if the program crashes.

Thanks.

Robo11
  • 45
  • 6

3 Answers3

3

Yes/no,

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

This can be found at Oracle

Just think about it as a finally block. The finally will always be executed.

"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."

This can be found at Oracle

Chris Bolton
  • 2,162
  • 4
  • 36
  • 75
0

No it will not.

Runtime.addShutdownHook gives more guarantees if you need them but still not 100% because it will not be called if JVM crashes/someone terminate JVM forcibly from outside.

Best possible solution here it to have wrapper process that starts your Java application, watches over it and does what you need when watched process terminates.

Sergey Alaev
  • 3,851
  • 2
  • 20
  • 35
0

If I understand your question correctly,I think it Wont close. The try block has to gracefully complete or catch some exception in order to close the resource. so it should be a checked exception. I believe if you catch a RuntimeException in your try with resources then the resource will be closed. But it wont close the resource with the thread or JVM crashes for issues like OOM.

GAK
  • 1,018
  • 1
  • 14
  • 33