Sunday, March 25, 2018

Learnings in handling input and output streams in Java

I learned it hard way that working with streams in Java can be tricky, specially when you are writing to an output stream. It happened to me a couple of times that I found that although I am writing to stream but still I lost some data. That happened because I forgot to close the stream. And sometimes I closed a stream which I should not have. Below I am providing some points that I have learnt while working with streams:

Flush the streams frequently: Main benefit of working with streams is you process the data as you receive from input stream and push the processed data into the output stream. So, you must flush your data into the output stream as you process. This ensures that the listener on the other end of the output stream gets the data continuously. And also make sure you flush the data when the processing is done to ensure even the last bits are sent to the output stream.

Close the stream only if you open it: It is a rule of thumb that you close any stream (input or output) only if you have open it. Simple reason is, if the caller method has opened the stream and passed it to you( in your method) then it is possible that caller can use it after your method call. Example is, input and output stream in a servlet is opened by the application container and then passed to the servlet, you don't have to close these streams. Container closes these streams when the http request is completed.
This includes the stream that you have created as wrapper on another stream.




No comments:

Post a Comment