๐ Java Resource Management: Closeable vs AutoCloseable
๐ฏ Objective
Understand the difference between Closeable
and AutoCloseable
in Java, when to use each, and how they behave in real-world scenarios like file I/O and JDBC.
๐ Overview
โ
Best Practices
๐งช Real-World Examples
๐ 1. File I/O with Closeable
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
๐ Why Closeable
?
FileReader
andBufferedReader
are designed to throwIOException
, soCloseable
fits naturally.Clean and restricted exception handling.
๐งฌ 2. JDBC with AutoCloseable
import java.sql.*;
public class JdbcAutoCloseableExample {
public static void main(String[] args) {
String url = "jdbc:h2:mem:testdb";
try (
Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("SELECT 1");
ResultSet rs = stmt.executeQuery()
) {
while (rs.next()) {
System.out.println("Result: " + rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
๐ Why AutoCloseable
?
JDBC resources throw
SQLException
, notIOException
.Allows full flexibility of
throws Exception
.
๐ ๏ธ 3. Custom Resource with AutoCloseable
class MyResource implements AutoCloseable {
public void use() {
System.out.println("Using MyResource...");
}
@Override
public void close() throws Exception {
System.out.println("Cleaning up MyResource...");
}
}
public class CustomResourceDemo {
public static void main(String[] args) {
try (MyResource res = new MyResource()) {
res.use();
} catch (Exception e) {
e.printStackTrace();
}
}
}
๐ When to use this?
Any object that needs deterministic cleanup (e.g., releasing a lock, stopping a timer, rolling back a transaction).
๐ก Did You Know?
๐ Try-With-Resources Order
Resources are closed in reverse order of declaration.
try (A a = new A(); B b = new B()) {
// use resources
}
// b.close() is called first, then a.close()
โ ๏ธ Suppressed Exceptions
If both the main try block and
close()
throw exceptions, the one fromclose()
is suppressed, and the first one is thrown.
Throwable primary = new IOException("Primary failure");
Throwable suppressed = new IOException("Suppressed during close");
primary.addSuppressed(suppressed);
๐ง Summary Table
๐ Interview Tip
โWhat happens if both the try block and
close()
throw exceptions?โ
The exception in
close()
is suppressed and stored inside the primary exception viaThrowable.addSuppressed()
.