Hassan Qayyum
Hassan Qayyum

Reputation: 91

Closing all streams in Java at once

Is there a way to close all streams or handles at once in Java without having references to them? Or is there a way to close all handles (streams) associated with particular File having reference of that File in Java?

Upvotes: 2

Views: 6673

Answers (2)

Socratic Phoenix
Socratic Phoenix

Reputation: 556

No

Without a reference to the stream, there's no way to invoke close() on it, same with any other object - without a reference to it, you can't actually do anything with it. I'm not completely sure how streams are handled internal, and to be honest, there is probably a way to do this using internals or reflection or JNI, but all of those should generally be avoided if a better solution exists.

Instead, you should look at the design of your program/code and try to re-design it to either:

  1. close() streams immediately after use, or
  2. Maintain a list of open streams yourself

If you're using an API that doesn't give you a reference to the stream, and doesn't close() the stream, and provides you no way to close() the stream, then that is a bug/design flaw in the API your are using.

If you have a reference to a stream at one point, but lose that reference and need to close it later, then you could simply set up some sort of registry to maintain a list of streams. An extremley simple example would be something like this:

public class StreamRegistry {
    private List<Closeable> streams = new ArrayList<>();

    public void register(Closeable closeable) {
        streams.add(closeable);
    }

    public void close() throws IOException {
         for(Closeable closeable : streams) {
             closeable.close();
         }
    }
    
}

Although you'd probably want to catch the IOException from close(), record it, and continue trying to close streams.

However, I would not recommend using a registry unless you absolutely have to. As @EJP and @Suresh Atta said in the comments to your question, if you're asking this kind of question, you should probably be trying to refactor/redesign your code to avoid this issue altogether and try and close() streams as soon as you're done with them. That said, without knowing exactly why you need to do this, I can't really do anything other than propose options.

Upvotes: 2

Sumit Das
Sumit Das

Reputation: 311

Best way is use some static code analysis tool like sonar. It will tell where are the places you have missed to close the open stream. If you have forget to open any stream, it will tell you that there is a blocker issue which have to fix.

For more details about sonar, you can use the given link.

Sonar Qube

Upvotes: 1

Related Questions