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?
}
}
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.
Generally it is not recommended to close the stream which is not associated to that class.
Following are the reasons,
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.
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.
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
No you don't have to do it because it may be used somewhere further in the code.
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.
Related
I am using Java 1.6.
I am facing some memory heap issues and in the heap dump I can see that ObjectOutputStream objects are consuming more memory.
In my application at some places, I have used ObjectOutputStream but missed to close the stream in some of the methods.
So will this impact the performance ??
Will the stream remain open and will it consume Heap Memory ??
Will Java close the stream when the method is finished where ObjectOutputStream is used but stream is not closed ??
No, java will not close the stream all by itself.
How badly leaving it open will affect your performance depends on the rest of the code. If the method is often, it will be a serious problem. Regardless of that, it's just way better practice to close your streams.
It's a great reason to upgrade to java 7, where you can write
try (ObjectOutputStream stream = ...) {
...
}
Here java will close the stream for you when you're done with it, no matter how that happens.
Off course you can achieve the same behaviour in java 6 but it's more work.
In Java 1.6, looking at the docs :
close
public void close()
throws IOException Closes the stream. This method must be called to release any resources associated with the stream.
must is pretty strong, so I would say that yes, you must call it.
We can have a look at the source :
public void close() throws IOException {
flush();
clear();
bout.close();
}
It does clean a few things. It also implements the interface AutoCloseable, which :
public interface AutoCloseable
A resource that must be closed when it is no longer needed.
So, call the close() method.
Note : Even if close() did nothing I would still call it to give a clear indication in the code that this is not to be used anymore, but that's probably a personal preference.
Adding some comments to Stef's great answer:
From another point of view, you may ask yourself: what is the reason for leaving the ObjectOutputStream open in some cases? If you don't use it anymore, then you should definitely close it as soon as possible. It is a good idea to follow this convention.
The close method makes sure that there are no references to the stream so the resources can be garbage collected; using it is definitely something you want to do in order to have a healthy memory space.
What I am usually doing is having a try {} finally {} without a catch {}:
public static void closeStream(OutputStream out)
{
if (out != null) out.close();
}
...
ObjectOutputStream out = null;
try
{
//do something
}
finally
{
closeStream(out);
}
You can of course use a catch block if you need to, or add throws to your method. Either way, this way you can be sure that stream resources are released.
I have some questions regarding java finalization.
For example I have one class FileHelper and this class is associated with reading file,writing file,etc.
Now my question is, I have one method writeFile() in FileHelper class.Now If I want to close that file
should I override the finalize() method and close the file or can I close the file inside the writeFile() method itself? Which is the right way to do? I have declared my File variable as a member variable. If overriding is a bad idea, then why do we want to override finalize() method? which scenario? I have read many articles,where they are saying to close system resources such as file,font etc..
The best practice is to close the file as soon as possible. If you have static method in FileHelper (assuming that your Helper is a bunch of static "helper" methods) I would close the file inside
static void writeFile(String fileName, String text) { // Exception
// Open file here
// write text
// close it
}
The purpose of overriding finalize is release the unmanaged resources e.g. files in case someone forget to do it. If someone use your helper this way
FileHelper fileHelper = new FileHelper(file);
fileHelper.writeFile(text);
// forgot to fileHelper.close();
and you have overridden the finalize and call close() inside when GC runs the file will be closed. The problems:
As I mention earlier file should be closed as soon as possible (but not sooner ;) )
It's indeterministic (No body knows when GC will start)
This should be used only to prevent the case when the caller forgets to close the file
The finalize() method would only get invoked when the Java Garbage Collector is about to reclaim the object. It is a bad practice to release file handle in the finalize method.
It may result in java.io.IOException: Too many open files as you cannot guarantee when the garbage collector would run.
A better option would be to close the file reader/writer object in the finally block. As it is guaranteed to run.
finally {
// Always close input and output streams. Doing this closes
// the channels associated with them as well.
try {
if (fin != null)
fin.close();
if (fout != null)
fout.close();
} catch (IOException e) {
}}
fin and fout are FileInputStream and FileOutputStream objects.
Using finalizers is a bad idea, in nearly all circumstances. The Java specs state that there is no guarantee that finalizers will ever be run. And even if they do, you have no control over when this may happen.
Using finalizers as the primary mechanism to close files is always a bad idea. Why? Because if the GC doesn't run for a long time, your application is liable to run out of file descriptors, and file open attempts will start failing.
The best way to deal with opened streams is to keep them in local variables and parameters, and use try { ...} finally to make sure that they are always closed when you have finished with them. Or in Java 7, use the new "try with resource" syntax.
If you need to put the stream in a member variable, you probably should make the parent class implement a close() method that closes the streams, and use try { ...} finally to make sure that the instances of the parent class get closed.
It should also be noted that there is little point using a finalizer to close "lost" streams. The stream classes that use external resources that need to be closed already have finalizers to do this.
Overriding finalize() is not a good practice. I would have done it in the code.
Hi all I understand that if we read bytes from an InputStream and we have finished reading all the bytes (or we do not intend to read to the end of stream), we must call close() to release system resources associated with the stream.
Now I was wondering if I read bytes and it throws a java.io.IOException, am I still required to call close() to release system resources associated with the stream?
Or is it true that on errors, streams are closed automatically so we do not have to call close() ?
The OS itself might close the streams and deallocate resources because the process (namely, the JVM) terminates, but it is not mandated to do so.
You should always implement a finally block where you close it in cases like these, e.g. like this:
InputStream is = null;
try {
is = new FileInputStream(new File("lolwtf"));
//read stuff here
} catch (IOException e) {
System.out.println("omfg, it didn't work");
} finally {
is.close();
}
This isn't really guaranteed to work if it threw in the first place, but you'll probably wanna terminate at that point anyway since your data source is probably messed up in some way. You can find out more info about it if you keep the InputStream's provider around, like, if I kept a ref to the File object around in my example, I could check whether it exists etc via File's interface, but that's specific to your particular data provider.
This tactic gets more useful with network sessions that throw, e.g., with Hibernate...
So of course we must try-catch-finaly any Closable resource.
But I came across some code which sins as follows:
java.util.Properties myProps = ... reads & loads (and doesn't close Stream!)
myProperties.store(new FileOutputStream(myFilePath), null);
System.exit(0);
java.util.Properties.store() flushes the underlying stream (the FileOutputStream)
Will this be enough?
Can you think of a scenario where the file won't be written? assuming that the method passes and no exception is being thrown in 'store'
It is enough in this specific case, but it is nevertheless very bad practice. The FileOutputStream should be closed, not merely flushed.
If you don't want open file references I would close the streams. Flushing only makes sure that all changes are written to file.
In my Java code, I start a new process, then obtain its input stream to read it:
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
FindBugs reports an error here:
may fail to close stream
Pattern id: OS_OPEN_STREAM, type: OS, category: BAD_PRACTICE
Must I close the InputStream of another process? And what's more, according to its Javadoc, InputStream#close() does nothing. So is this a false positive, or should I really close the input stream of the process when I'm done?
In this case, you want to close() the Reader, which will close its underlying streams. Yes, it's always good practice to close streams, even if at the moment you know the implementation you're looking at doesn't do anything (though, in fact, it does here!). What if that changed later?
FindBugs is only there to warn about possible errors; it can't always know for sure.
Finally yes, your Java process owns the process and Process object you spawned. You most definitely need to close that and the output stream. Nobody else is using them, and, it's important to do such things to avoid OS-related stream funny business.
InputStream is an abstract class - just because its implementation does nothing doesn't mean that the actual type of object returned by process.getInputStream() doesn't.
It's possible that failing to close the input stream in this particular case would do no harm - but I personally wouldn't count on it. Close it like you'd close any other input stream. Aside from anything else, that makes your code more robust in case you ever decide to change it to read from something else - it would be all too easy to (say) read from a file instead, and not notice that you're not closing the FileInputStream.
I think its always a good practice to close all the streams you open. Preferably in the finally{} block. Since it does nothing as java says, why not call the close() method. Its of no harm.