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”方法中,我創(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python操作redis实例_Java
- 下一篇: Rust 从入门到精通12-集合