ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-使用流关闭套接字

2019-11-19 23:00:47  阅读:274  来源: 互联网

标签:sockets java garbage-collection


我的以下问题非常简单.

这是我的代码:

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有