[英]Closing BufferedReader without closing wrapped stream
I'm currently writing a program that communicates with a server using TCP sockets. 我目前正在编写一个使用TCP套接字与服务器通信的程序。 Part of that requires sending information back and forth through several methods.
其中一部分需要通过几种方法来回发送信息。 However, I do not want to open up a new socket connection for each request, but I can't guarantee the number or the order of the requests.
但是,我不想为每个请求打开一个新的套接字连接,但是我不能保证请求的数量或顺序。 In order to handle this, I simply keep one socket instance that gets reused a lot.
为了解决这个问题,我只保留了一个可以大量重用的套接字实例。
However, in order to read the data I use BufferedReader
wrapper classes. 但是,为了读取数据,我使用
BufferedReader
包装器类。 Because I reuse the same socket, I can't call close()
on the reader, or I'll close the socket stream as well. 因为我重用了相同的套接字,所以无法在读取器上调用
close()
,否则我也将关闭套接字流。
Do I need to call close()
on the BufferedReader if I don't want to close the underlying stream? 如果我不想关闭基础流,是否需要在BufferedReader上调用
close()
? Will I cause a memory leak by not doing this? 不这样做会导致内存泄漏吗? If I do need to call
close()
how can I return the memory without closing the socket's stream? 如果确实需要调用
close()
如何在不关闭套接字流的情况下返回内存?
Note: I will close the underlying stream at program termination, this question isn't about that. 注意:我将在程序终止时关闭基础流,这个问题与之无关。
Don't close the BufferedReade
. 不要关闭
BufferedReade
。 More important , don't discard the BufferedReader
; 更重要的是 ,不要丢弃
BufferedReader
; instead, pass it around rather than the SocketInputStream
. 而是传递它,而不是
SocketInputStream
。
A BufferedReader
, as its name implies, has an internal buffer. 顾名思义,
BufferedReader
具有内部缓冲区。 When you read from it, it tries to fill that buffer from the underlying Reader
. 从中读取时,它会尝试从基础
Reader
填充该缓冲区。 Which means that, if you discard it, those bytes are gone. 这意味着,如果丢弃它,这些字节将丢失。
And now some unasked advice: 现在有一些未提出的建议:
Reader
? Reader
吗? Most communication protocols are better implemented using a DataInputStream
/ DataOutputStream
. DataInputStream
/ DataOutputStream
可以更好地实现大多数通信协议。 With a Reader
you're limited to character data (and in the case of BR
, lines of character data). Reader
您只能使用字符数据(对于BR
,是字符数据行)。 Reader
on top of an InputStream
is to use the two-argument variant of InputStreamReader
: new InputStreamReader(in, "UTF-8")
(you can use an encoding other than UTF-8, but have a good reason ). Reader
上的顶部InputStream
是使用两个参数的变异体InputStreamReader
: new InputStreamReader(in, "UTF-8")
您可使用UTF-8编码,但有一个良好的原因 )。 BufferedInputStream
rather than a BufferedReader
, because the translation from stream to reader may involve multiple reads. BufferedInputStream
而不是BufferedReader
,因为从流到阅读器的转换可能涉及多次读取。 If you want readLine()
, you can always use both. readLine()
,则可以始终使用两者。 finally
or try-with-resources. finally
或try-with-resources中关闭套接字 。 See this for more info.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.