我的以下問題非常簡單.
這是我的代碼:
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