Sobes.tech
Junior

Why is it important to close resources in Java?

sobes.tech AI

Answer from AI

It is important to close resources (file streams, network sockets, database connections, etc.) for several reasons:

  • Prevent resource leaks: Unclosed resources remain in memory or the operating system, not available for other parts of the application or system. Over time, this can lead to exhaustion of system resources (memory, file descriptors), slowdown, or crashes.
  • Release system resources: Closing a resource releases associated system resources, allowing other processes to use them.
  • Proper completion of operations: Some operations (e.g., writing to a file) may not be fully completed until the resource is explicitly closed (e.g., buffered data is flushed to disk).
  • Network connections: Unclosed network connections can hold ports and consume resources on both ends.
  • Database connections: Unclosed database connections can quickly exhaust the connection pool and cause service denial for other parts of the application.

To ensure resources are closed reliably, use try-with-resources (since Java 7):

// Example of try-with-resources
try (java.io.FileInputStream fis = new java.io.FileInputStream("file.txt")) {
    // Read from file
} catch (java.io.IOException e) {
    // Handle exception
} // fis is automatically closed here

If try-with-resources is not available (e.g., working with legacy code or libraries not implementing AutoCloseable), use finally block:

// Example with finally
java.io.FileInputStream fis = null;
try {
    fis = new java.io.FileInputStream("file.txt");
    // Read from file
} catch (java.io.IOException e) {
    // Handle exception
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (java.io.IOException e) {
            // Handle close exception
        }
    }
}

Using try-with-resources is preferred as it is more concise and guarantees resource closure even if exceptions occur.