日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java的流套接_java-使用流关闭套接字

發(fā)布時間:2023/12/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java的流套接_java-使用流关闭套接字 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我的以下問題非常簡單.

這是我的代碼:

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”方法中,我創(chuàng)建了一個BufferedWriter,用于將“ OK”字符串寫入遠(yuǎn)程源.稍后,我關(guān)閉套接字.

因此,我的簡單問題是:據(jù)我了解,由于我關(guān)閉了套接字,因此鏈條應(yīng)如下所示:

關(guān)閉插座—->關(guān)閉的是os —->關(guān)閉作家

因此,通過關(guān)閉Socket,我也關(guān)閉并允許GC釋放BufferedWriter.我是正確理解還是做錯了什么?對于我用其他方法(即BufferedInputStream)初始化的所有作者和讀者,是否都是這樣?通過在方法末尾將這些變量設(shè)置為null,我是否在幫助GC區(qū)分應(yīng)釋放的內(nèi)容?還是我不應(yīng)該這樣做?

謝謝!

解決方法:

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包裝在套接字輸出流中,但是套接字不知道.它無法關(guān)閉它.

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

不,不. ping()返回時,BufferedWriter可用于GC,并且永遠(yuǎn)不會關(guān)閉.

Am I understanding this correctly

沒有.

or doing something wrong?

是.您不應(yīng)該為每條消息創(chuàng)建一個新的BufferedWriter.您應(yīng)該在插座的使用壽命中使用同一插座,然后關(guān)閉它而不是插座.同樣,在套接字的整個生命周期內(nèi),只能使用一個輸入流或Reader.否則,您可能會丟失其緩沖區(qū)中的數(shù)據(jù).

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?

您不應(yīng)執(zhí)行任何操作.

標(biāo)簽:sockets,java,garbage-collection

來源: https://codeday.me/bug/20191119/2039658.html

總結(jié)

以上是生活随笔為你收集整理的java的流套接_java-使用流关闭套接字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。