socket and bufferedreader close()

?

-

i have a

socket = ...
br = new BufferedReader(...


when i close, should i close both br and socket? if so, in which order?
if not, which one should be closed?
 
A

Arnaud Berger

Hi,

You should obviously close the reader first, because if the stream it is
reading from is closed ,it will probably get you IOException .

You should also close the socket.

Regards,

Arnaud
 
S

Steve Horsley

- said:
i have a

socket = ...
br = new BufferedReader(...


when i close, should i close both br and socket? if so, in which order?
if not, which one should be closed?

Closing the BufferedReader should also close the underlying Reader, which
should close the underlying InputStream which should close the underlying Socket.

But if you also called the socket's getOutputStream() method, you should also
close that stream (or any wrappers you put round it) to avoid leaving an open
InputStream / file handle. I think that closing the socket doesn't close the
input and output streams above it.

Steve
 
E

Esmond Pitt

Steve said:
Closing the BufferedReader should also close the underlying Reader, which
should close the underlying InputStream which should close the
underlying Socket.

But if you also called the socket's getOutputStream() method, you should
also
close that stream (or any wrappers you put round it) to avoid leaving an
open
InputStream / file handle. I think that closing the socket doesn't close
the input and output streams above it.

Always close the output stream first, as this will flush any pending
data. You can then close the input stream and the socket if you want to
but there is no need, you won't be able to use them anyway.
 
S

Steve Horsley

Esmond said:
Always close the output stream first, as this will flush any pending
data.

Thanks for the tip.
You can then close the input stream and the socket if you want to
but there is no need, you won't be able to use them anyway.

Are you sure this doesn't constitute a handle leak if you don't
close the input stream too? I was sure I got "too many open files"
errors once after opening and closing lots of sockets but forgetting
to close the associated streams.

Steve
 
E

Esmond Pitt

Steve said:
Are you sure this doesn't constitute a handle leak if you don't
close the input stream too? I was sure I got "too many open files"
errors once after opening and closing lots of sockets but forgetting
to close the associated streams.

No, closing either of the streams also closes the socket.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top