What is a resource leak?

Tim Rohaly

Garbage collection manages only memory, not other system resources. If your Java program has plenty of free memory, garbage collection will not be triggered automatically. Usually, however, there are other resources that are more limited than memory. For example, all OSes have limits on the number of sockets, file handles, etc. that can be open. Sometimes this limit is quite low. This is true even on a desktop, e.g. if your system has 128KB of memory, your Java program can easily allocate all the available file handles without coming near to filling up the heap. If this happens, your Java program will fail. This is what we call a resource leak; the unintentional maintenence of references to non-memory resources.

This is why it is important in Java to explicitly manage non-memory resources. Classes which utilize non-memory resources should provide ways to explicitly allocate/deallocate those resources, independent of garbage collection. For example Socket, InputStream and OutputStream each provide explicit close() methods for deallocation of file descriptors, Window provides a dispose() method to free the window handle, etc. The way to properly use these classes is to allocate using the constructor, then deallocate using the appropriate method (deallocation is preferably done in a finally{} block, so it will execute whether or not an exception is thrown during use). These classes do release these non-memory resources in their finalize() method, but remember that the finalizer only gets called by the garbage collector, and if the object is never collected, it will never be finalized, hence will never release the resources.