我需要关闭套接字的 reader 吗?

Do I need to close the reader of the socket?

因此在 Java 中创建一个服务器端应用程序。

关于关闭连接,我只是想知道如果我在 reader 之前关闭套接字会发生什么。

例如服务器端

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

}

在套接字输入流周围实例化的缓冲reader是否会随着套接字关闭而关闭,还是我手上有潜在的内存泄漏?

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

不,因为 buffered-reader 只保存套接字提供的流,它不知道该流的状态何时改变。

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

不是真的,因为缓冲区与 reader 的生命周期相关。即使关闭 reader 导致缓冲区被释放,它也需要等待垃圾回收可用于其他对象。

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

是的,或者更确切地说,它的底层 socket.getInputStream() 将关闭,BufferedReader 会在您下次调用它时注意到。

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

没有

但是您应该关闭的不是套接字或 Reader,而是您包裹在套接字周围的最外面的 WriterOutputStream,以确保它被冲洗掉。

关闭套接字的输入流或输出流都会关闭套接字的另一个流,关闭套接字也会关闭两个流。