简体   繁体   中英

Do I need to close the reader of the socket?

So creating a serverside app in Java.

In terms of closing the connection, I'm just wondering what happens if I close the socket before the reader.

For example server side

//imports
public static void main(String[] args) {
    Socket socket = null;
    try {
        ServerSocket servsocket = new ServerSocket(8080);
        socket = servsocket.accept();
    //connection established
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   } catch(Exception e) {
       e.printStackTrace();
   } finally {
        socket.close();
   }

}

Will the bufferedreader instantiated around the input stream from the socket close along with the socket closing, or do I have a potential memory leak on my hands?

Will the bufferedreader instantiated around the input stream from the socket close along with the socket closing

Yes, or rather its underying socket.getInputStream() will close, which the BufferedReader will notice next time you call it.

or do I have a potential memory leak on my hands?

No.

But what you should close is not the socket or the Reader but the outermost Writer or OutputStream that you have wrapped around the socket, to ensure it gets flushed.

Closing either the input or output stream of a socket closes the other stream of the socket, and closing the socket closes both streams.

Will the bufferedreader instantiated around the input stream from the socket close along with the socket closing,

No, since the buffered-reader only holds the stream provided by the socket, it does not know when the state of that stream changes.

or do I have a potential memory leak on my hands?

Not really since the buffer is tied to the lifetime of the reader. Even if closing the reader causes the buffer to be disposed, it would need to wait for garbage-collection to be available for other objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM