Much like a java class instance, a stream usually has a simple life cycle as follows:

1) Open it.  Often this locks or “borrows” an operating system resource behind the scenes, such as a file handle or a socket.

2) Read from or write to it until done.  Sometimes the stream is lent to another method or class while this occurs, but responsibility for the stream is still with the code that opened the stream.

3) Close it, releasing any system resource.  The close must occur even if there is a serious error.  Normally the same code that opened the stream is responsible for closing it.

It's important to understand this sequence because Streams are used regularly in Java.

Trap: Unless you are downloading a very large file over the internet, reading or writing from a stream doesn't usually take very long, so a stream should only be open for a short while.  If the code is opening streams and leaving them open, storing references to them while they are still active, it's possible the design needs re-evaluation.  Software that keeps streams open can run out of operating system resources.

blog comments powered by Disqus