sdm
sdm

Reputation: 1246

Should I close a stream which I did not create?

If I have stream (InputStream or OutputStream) which I did not create but was rather passed to my method as a parameter, should I be closing that stream? Here's an example:

void method(InputStream in) {
    try {
    //Do something
    }
    finally {
        if(in != null) { 
        in.close();    //Is this needed and correct?
    }    
}

Upvotes: 3

Views: 1388

Answers (5)

vikingsteve
vikingsteve

Reputation: 40378

Really, "it depends".

As a general rule, you should not close a stream that you didn't have responsibility for opening, but to give a correct answer we would have to understand the context.

It's very possible that the delegation of responsibility requires your method to consume from and close the stream - if this is the case then it should be explicit in the code.

If your method is named readFromStreamAndClose(InputStream in) then the fact that your method closes the stream is very obvious.

In the case that you open the stream yourself, you can always use a try-with-resources block which will close the stream for you - at the same level of abstraction as it was created. In this case - your method (which is called at a lower level than when the stream was opened) should not close the stream.

Upvotes: 3

Vijayakumar
Vijayakumar

Reputation: 303

Generally it is not recommended to close the stream which is not associated to that class.

Following are the reasons,

  1. Streams passed to that method may be used in some other place. Reusable streams are available in java. If the stream is closed it cannot be reopened and reused.
  2. In case of Exception when closing the stream you don't know how to handle that. Because you are dealing with general inputstream and it may come from any place like File, Network etc.

The class opens the stream is responsible for closing it.

Upvotes: 1

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

You do document the method with: "Closes the stream" and change the name method to like readAndClose.

Or create a parameter boolean closeStream and close if true.

Also if the stream doesnt support mark/seek/reset there's no reason to keep it open.

Upvotes: 0

Muro
Muro

Reputation: 1

No you don't have to do it because it may be used somewhere further in the code.

Upvotes: 0

abhinavsinghvirsen
abhinavsinghvirsen

Reputation: 2014

I don't think that the JVM spec makes any guarantee about that. You really are supposed to finally close these resources.

When the process ends, the operating system will release all resources associated to it (including memory, file handles, and network sockets).

There are OS facilities to check about open files and streams

Upvotes: 0

Related Questions