Reputation: 1800
I'm currently writing a program that communicates with a server using TCP sockets. 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. Because I reuse the same socket, I can't call close()
on the reader, or I'll close the socket stream as well.
Do I need to call close()
on the BufferedReader if I don't want to close the underlying stream? 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?
Note: I will close the underlying stream at program termination, this question isn't about that.
Upvotes: 1
Views: 1688
Reputation: 39606
Don't close the BufferedReade
. More important, don't discard the BufferedReader
; instead, pass it around rather than the SocketInputStream
.
A BufferedReader
, as its name implies, has an internal buffer. When you read from it, it tries to fill that buffer from the underlying Reader
. Which means that, if you discard it, those bytes are gone.
And now some unasked advice:
Reader
? Most communication protocols are better implemented using a DataInputStream
/DataOutputStream
. With a Reader
you're limited to character data (and in the case of BR
, lines of character data).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).BufferedInputStream
rather than a BufferedReader
, because the translation from stream to reader may involve multiple reads. If you want readLine()
, you can always use both.finally
or try-with-resources. See this for more info.Upvotes: 3