gpt4 book ai didi

java - 使用流关闭套接字

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:17 25 4
gpt4 key购买 nike

我的以下问题非常简单。

这是我的代码:

public class Protocol implements Runnable {

private SSLSocket socket = null;
private InputStream is = null;
private OutputStream os = null;

...

public Protocol(Socket s) {
socket = (SSLSocket)s;
is = socket.getInputStream();
os = socket.getOutputStream();
}


@Override
public void run() {

...
ping();
socket.close();
...
}


public void ping() {

BufferedWriter writer;
try {
writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write("OK");
}
catch (IOException e) { System.out.println("ERROR: " + e.getLocalizedMessage()); }
finally { writer = null; }
}

我知道我没有包含很多源代码,但这应该足以回答这个问题。如您所见,在“ping”方法中,我创建了一个 BufferedWriter,用于将“OK”字符串写入远程源。稍后,我关闭套接字。

所以我的简单问题是——据我了解,由于我关闭了套接字,链条应该是这样的:

Close socket ----> 关闭 is 和 os ----> 关闭 writer

因此,通过关闭 Socket,我也关闭并允许 BufferedWriter 被 GC 释放。我是理解正确还是做错了什么?对于我在其他方法(即 BufferedInputStream)中初始化的所有作者和读者来说都是这样吗?通过在方法结束时将这些变量设置为 null,我是否在帮助 GC 区分应该释放的内容?或者我不应该这样做?

谢谢!

最佳答案

From what I understand, since I close the socket, the chain should go like this:

Close socket ----> which closes is and os ----> closes writer

没有。 BufferedWriter 包裹在套接字输出流周围,但套接字不知道这一点。它无法关闭它。

So, by closing the Socket, I am also closing and allowing the BufferedWriter to be freed by the GC.

没有也没有。 BufferedWriterping() 返回后立即可用于 GC,并且它永远不会关闭。

Am I understanding this correctly

没有。

or doing something wrong?

是的。您不应该为每条消息创建一个新的 BufferedWriter。您应该在套接字的整个生命周期内使用同一个套接字,并关闭 而不是套接字。同样,您应该在套接字的生命周期内只使用一个输入流或 Reader。否则,您可能会丢失其缓冲区中的数据。

Is this true for all writers and readers that I initialize in other methods (i.e. BufferedInputStream).

没有。

And by setting these variables null at the end of the method, am I helping the GC to distinguish between what should be freed?

没有。你只是在浪费时间和空间。该方法无论如何都即将退出,因此它的所有局部变量都消失了。

Or should I not do this?

你不应该做任何事情。

关于java - 使用流关闭套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31930930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com