简体   繁体   中英

What exactly are resource leaks?

I have heard people many times use the term "Resource leak". I'm sure this is a global phenomenon, though for the purpose of this answer, I will stick to those in Java. Take for example the following code :

public void append(String text) throws IOException
{
    BufferedWriter buffWriter = new BufferedWriter(new FileWriter("tf2rocks.imnotkidding", true));
    buffWriter.write(event);
    buffWriter.close();
}

In the above snippet, there is a resource leak, as if an IOException was thrown by write() , close() will never be called.

Now my question is : What exactly is a resource leak? How can they cause harm to me?

If each java program is executed in it's own instance of the JVM, in an enclosed environment, how exactly can these "resource leaks" cause me harm? Is it possible for other malicious programs to take advantage of this?

Classes implementing java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed. All operating system have limits on the number of sockets, file handles.etc. that can be opened at particular instance of time. If you don't close the resources then you are unnecessary keeping them open and if you continue to keep opening more and more resources without closing them then after some time operating system will not be able to allocate more resources.

You are right with your example. Think from OS perspective, where you have predefined file/sockets handles that you could create ie say this many files can be open at a time. Now if you keep on opening multiple files, you may go out of number of files that can be open.

So although, its JVM but JVM alone can't run without the help from OS. File handler/descriptor is just one of the example.

If it's memory, then you don't have you worry as it will be handled by GC automatically but GC wont take care of resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM