Consequences of not closing byte streams
byte, java, stream
Solution
This is not only byte streams. This concerns anything implementing `Closeable`.
As the documentation states:
The close method is invoked to release resources that the object is holding (such as open files).
Whether a `Closeable` holds system resources or not, the rule of thumb is: do not take the chance. `.close()` it correctly, and you'll be ensured that such system resources (if any) are freed.
Typical idiom (note that `InputStream` implements `Closeable`):
final InputStream in = whateverIsNeeded;
try {
workWith(in);
} finally {
in.close();
}
With Java 7 you also have `AutoCloseable` (which `Closeable` implements) and the try-with-resources statement, so do:
try (
final InputStream in = whateverIsNeeded;
) {
workWith(in);
}
This will handle closing `in` for you.
Again: don't take the chance. And if you don't use JDK 7 but can afford Guava, use `Closer`.
Problem
The question says it all. What are the consequences of not closing the various byte streams? It is very much emphasized to always do so, but there is no mention of how it causes problems. Can someone please explain what actually happens?