I would like to know when does a stream close if its not closed manually. By this I mean, will the stream be closed if the scope of its reference is no more?
Consider the following sample scenario.
Class A{
InputStream in;
OutputStream out;
A(){
// Initialize and create the streams.
}
...
}
Class B{
public void myMethod(){
A a = new A();
System.out.println("End of my method.")
}
...
}
Here, once I am done with the stream, I am exiting myMethod()
but the program which in turn the process, is not terminated and goes on with other operations.
I did not close the streams. Will it be closed automatically once the scope of the reference to class A ends? (ie. When myMethod()
ends)? Does GC takes care of that? Also, I read that the streams will be closed once the process ends and the system releases all the resources held for it for other processes. How can we check whether the stream is open or not? Are there any linux commands or options from Java to check that?
Any help is appreciated!
The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.
IO Resources. Under the hood, this method opens a FileChannel instance and then closes it upon stream closure. Therefore, if we forget to close the stream, the underlying channel will remain open and then we would end up with a resource leak.
Streams have a BaseStream. close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files. lines(Path, Charset)) will require closing.
You should always close a stream in order to free open resources on your OS. Opening a stream always returns an identifier which you can use to close it wherever you are in your code (as long as the identifier is valid), whether their from another method or class.
In the case of FileInputStream
there's a finalize()
method that will free resources when the stream is garbage collected.
Not that you can or should rely on that. It's just what FileInputStream
does. SocketInputStream
on the other hand overrides finalize()
to explicitly do nothing, relying on Socket
to close the resources (and Socket
doesn't have a finalize()
method).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With