Is it necessary to close input/output streams created from a socket's IO streams when the socket closes?
java, sockets
Solution
If any IO streams or reader/writers is created from socket's input or output stream, is it necessary to close them before or after socket is closed?
You should close the outermost `OutputStream` or `Writer` you have created from the socket output stream. That will flush the stream and close the socket and its input stream. Closing any other aspect of the socket, such as its direct output stream, its input stream or anything wrapped around it, or the socket itself, accomplishes most but not all of that: specifically, closing the input stream before the output stream as you have in your example prevents the output stream being flushed and so can lose data.
Calling `shutdownInput()` or `shutdownOutput()` immediately before a close is always redundant.
Problem
``` private val in = new BufferedReader(new InputStreamReader(con.getInputStream())) private val out = new PrintWriter(con.getOutputStream(), true) try { while (true) { if (in.readLine() == null) throw new IOException("connection reset by peer") } } catch { case e: Exception => } finally { // Is this necessary? in.close() out.close() // Close socket con.shutdownInput() con.shutdownOutput() con.close() } ``` If any IO streams or reader/writers is created from socket's input or output stream, is it necessary to close them before or after socket is closed?