编程语言
首页 > 编程语言> > java-使用流关闭套接字

java-使用流关闭套接字

作者:互联网

我的以下问题非常简单.

这是我的代码:

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”字符串写入远程源.稍后,我关闭套接字.

因此,我的简单问题是:据我了解,由于我关闭了套接字,因此链条应如下所示:

关闭插座—->关闭的是os —->关闭作家

因此,通过关闭Socket,我也关闭并允许GC释放BufferedWriter.我是正确理解还是做错了什么?对于我用其他方法(即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.

不,不. ping()返回时,BufferedWriter可用于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?

您不应执行任何操作.

标签:sockets,java,garbage-collection
来源: https://codeday.me/bug/20191119/2039658.html