2

When reading beginner books on Java, I have read that a stream must always be closed once it is no longer required. Why is this the case? What's wrong with leaving it open?

Consider the example below:

 import java.io.*;
 public class SOStreamTest {

public static void main(String[] args){

    try{

        FileWriter writer = new FileWriter("Foo.txt");
        writer.write("hello foo!");
        //Writer.close();         <-!Line in Question -->
        }catch(IOException ex){
            ex.printStackTrace();
        }
}
}

As expected a warning message arises, 'resource leak: "writer" is never closed.'

RamanSB
  • 1,162
  • 9
  • 26

4 Answers4

2

You know on your Windows PC and you try to delete a file but it's in use by another program? That's one reason why you should always close File input or output streams.

Another example, for Linux this time, is that each File input or output stream requires something called a file handle. A given linux system will only allow a certain number of file handles to exist, and if you reach the maximum, bad things can happen.

When you close the stream, the file handle is released.

Other input and output streams can cause similar issues, for example failing to close a network stream could leave open a connection to another machine. Do this a couple of thousand times and you will run out of ports or kill the machine you are connecting to.

user1886323
  • 1,179
  • 7
  • 15
2

For one thing, you're expecting that your application will end at the bottom of main, however main is a normal method and may be called by other code which continues to run.

The reason you don't want streams to stick around is that they tend to be associated with an OS resource, which is a lot more constrained than memory.

Sockets are even more troublesome as you might hold onto resources for both your program, and the remote host.

Daniel
  • 4,481
  • 14
  • 34
1

The importance of closing your streams can be reduced to two one main points:

  • The first is that streams are usually tied to some system resource (sockets, files, database connections) which, in general, it's a good practice to be handled as an expensive asset since it may be shared by other processes or even slow down the system.

  • Also, if you do not close a stream, it's in memory representation will be kept alive as there would be no hints telling the garbage collector this objected can be deleted.

So, by closing a stream you are using wisely both a system resource and your process' memory space.

EDIT: As pointed in the comments section below, what I said about garbage collection is wrong. It might happen however, that a stream may be closed before being destroyed by GC as many basic streams (at least in Java) include a call to close() on their finalize() methods. See this SO thread on this very topic.

Roney Gomes
  • 497
  • 4
  • 13
0

One of most common reason is to ensure that everything will be written in out output.

Granting to our application access to write data in file can take some time. So to avoid requesting it each time to write single byte, we are using buffer like BufferedWriter in which we store large portion of data, and when it is full it will ask for writing access automatically, write its stored data, and clean buffer.

But in situation where buffer is not full and we don't have more data to write, we need to explicitly inform buffer to write data to file. We can do it by calling its flush method, or by calling close method which implicitly will call flush. Without it, our file will not contain part currently stored in buffer.

Pshemo
  • 122,468
  • 25
  • 185
  • 269