using closed resource in try-with-resource clause

Table of Contents

In java, stuff as in

try(stuff){
    statement;
    aThread.start();
}
catch(){}

would be freed after the try clause is over. If you passed some of the stuff to aThread, they probably wouldn’t work,

1. example

        try {
        ServerSocket myServerSocket = new ServerSocket(portNumber);
        while(true){
                     Socket aClientSocket = myServerSocket.accept();
                     PrintWriter output = new PrintWriter(aClientSocket.getOutputStream(),true);
                     BufferedReader input = new BufferedReader(new InputStreamReader(aClientSocket.getInputStream()));

                    System.out.println("Connection established with a new client with IP address: " + aClientSocket.getInetAddress() + "\n");
                    output.println("Connection established with Server at IP address: " + aClientSocket.getInetAddress() + ". This is server " + myServerSocket.getInetAddress());
                    String[] args = input.readLine().split(" ");
                    // output.println(args[0]);
                    // Tests batch = new Tests(args,aClientSocket);
                    Tests batch = new Tests(args,output);
                    // batch.run();
                    batch.start();

                    System.out.println(output);
                    // output.println("EOF");
                    }
                } catch (IOException e) {
                    System.out.println("Exception caught when trying to listen on port " + portNumber + " or listening for a connection");
                    System.out.println(e.getMessage());
                }
while(true){
    try(
        ServerSocket myServerSocket = new ServerSocket(portNumber);
        Socket aClientSocket = myServerSocket.accept();
        PrintWriter output = new PrintWriter(aClientSocket.getOutputStream(),true);
        BufferedReader input = new BufferedReader(new InputStreamReader(aClientSocket.getInputStream()));
         ){
        System.out.println("Connection established with a new client with IP address: " + aClientSocket.getInetAddress() + "\n");
        output.println("Connection established with Server at IP address: " + aClientSocket.getInetAddress() + ". This is server " + myServerSocket.getInetAddress());
        String[] args = input.readLine().split(" ");
        // output.println(args[0]);
        // Tests batch = new Tests(args,aClientSocket);
        Tests batch = new Tests(args,output);
        // batch.run();
        batch.start();

        System.out.println(output);
        // output.println("EOF");
    } catch (IOException e) {
        System.out.println("Exception caught when trying to listen on port " + portNumber + " or listening for a connection");
        System.out.println(e.getMessage());
    }
}

Backlinks

Author: Linfeng He

Created: 2024-04-03 Wed 23:18