Thor
Thor

Reputation: 13

Does a server connection stay open if created inside a method?

Sorry for the noob question but I am creating a client-server application.

If I create the connection from the client to the server within a method in the main class, would that connection stay open after the method is done executing?

So far I have a GUI that asks for the host name which then calls the Connect method. After the method has returned and the program carries on executing, does the connection inside the method stay open?

public static void main(String[] args) {
    ConnectionGUI connect = new ConnectionGUI();
}
public boolean Connect(String hName) {
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    try {
        clientSocket = new Socket(hName, 16000);
        out = new PrintWriter (clientSocket.getOutputStream(), true);
        in = new BufferedReader (new InputStreamReader(clientSocket.getInputStream()));
        return true;
    } catch(Exception e) {
        return false;
    }
}

Upvotes: 1

Views: 56

Answers (3)

Brenann
Brenann

Reputation: 94

Yes it does. Objects that call methods as behaviors still leave behind elements of the method they use. Java is memory safe, so when your object is no longer in use, and the methods of the object have for example, opened a connection, the connection will stay open, but the object will be deleted...this is because of the Garbage Collector in java.

Fix:

Override the finalize method in the universal super class(java.lang.Object) with your own finalize(), that will close the connection when the object is no longer in use. Your finalize method will be called by the Garbage Collector when it is going to delete your object, and will close the connection.

Upvotes: 0

jrtapsell
jrtapsell

Reputation: 7001

Would the connection stay open

Yes, it would, there is no call to close, so until the program stops the socket will be left open.

How do I prevent this leaking resources

You use try-with-resources to create a block which has access to an AutoCloseable resource, and which automatically closes it once the block is left, even if a Throwable is thrown.

Upvotes: 1

dillius
dillius

Reputation: 516

It would be best to ensure the Socket is getting closed.

You can do this either by adding a finally block:

 finally {
        clientSocket.close();
 }

Or by instead using try-with-resources

try(Socket clientSocket = new Socket(hName, 16000)) {
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        return true;
    }catch(Exception e){
        return false;
    }

Upvotes: 1

Related Questions