Close Resources Automatically in Java



In this article, we will learn to close resources automatically in Java. Resource management becomes important in Java programming to prevent memory leaks and system instability. Java provides several options for closing resources automatically: files, database connections, and network sockets.

The Problem with Manual Resource Closure

Traditionally, developers needed to manually close resources using try-finally blocks. This method is error-prone because it's easy to forget to close resources, and exception handling can be complicated:

FileInputStream fis = null;
try {
    fis = new FileInputStream("file.txt");
} finally {
    if (fis != null) {
        fis.close();
    }
}

How to close resources automatically in Java?

The following are the two different approaches to close resources automatically in Java:

Let us create a table named MyPlayers in the MySQL database using the CREATE statement as shown below ?

CREATE TABLE MyPlayers(
   ID INT,
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Date_Of_Birth date,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255),
   PRIMARY KEY (ID)
);

Now, we will insert 7 records in the MyPlayers table using INSERT statements ?

insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');

Using Try-with-Resources

We can close resources automatically using the try-with-resources in JDBC. It is a try statement with one or more resources declared at try, where the resource is an object that should be closed once it is no longer required.

We can declare multiple resources in this, and all those will be closed at the end of the statement automatically. The objects/resources we declare in this should implement java.lang.AutoCloseable or java.io.Closeable, interfaces or extend the java.lang.AutoCloseable class.

Syntax

The following is the syntax of the try-with-resources:

try(Declaration of resource){
   body.....
} catch (SQLException e) {
   e.printStackTrace();
}

In JDBC, we can use java.sql.CallableStatement, Connection, PreparedStatement, Statement, ResultSet, and RowSet in try-with-resources statement.

Example

Below is an example to show the use of the try-with-resources statement in JDBC ?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TryWithResources_Example {
   public static void main(String args[]) {
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      System.out.println("Connection established......");
      //Registering the Driver
      try(Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      Statement stmt = con.createStatement(); ) {
         try(ResultSet rs = stmt.executeQuery("select * from MyPlayers");) {
            //Retrieving the data
            while(rs.next()) {
               System.out.print(rs.getInt("ID")+", ");
               System.out.print(rs.getString("First_Name")+", ");
               System.out.print(rs.getString("Last_Name")+", ");
               System.out.print(rs.getDate("Date_Of_Birth")+", ");
               System.out.print(rs.getString("Place_Of_Birth")+", ");
               System.out.print(rs.getString("Country"));
               System.out.println();
            }
         } catch (SQLException e) {
               e.printStackTrace();
         }
         } catch (SQLException e) {
            e.printStackTrace();
      }
   }
}

Output

Connection established......
1, Shikhar, Dhawan, 1981-12-05, Delhi, India
2, Jonathan, Trott, 1981-04-22, CapeTown, SouthAfrica
3, Kumara, Sangakkara, 1977-10-27, Matale, Srilanka
4, Virat, Kohli, 1988-11-05, Mumbai, India
5, Rohit, Sharma, 1987-04-30, Nagpur, India
6, Ravindra, Jadeja, 1988-12-06, Nagpur, India
7, James, Anderson, 1982-06-30, Burnely, England
8, Ryan, McLaren, 1983-02-09, Kumberly, null

Using Cleaner API

The Cleaner API (added in Java 9) offers a safer and more reliable means of handling resource cleanup than the deprecated finalize() method. It automatically frees resources (such as file handles, database connections, or network sockets) when they become unreachable.

Syntax

The following is the syntax for cleaner API implementation:

public class ResourceHandler implements Runnable {
    private final Resource resource;    
    public ResourceHandler(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        // Cleanup logic
        resource.close();
    }
}
Cleaner cleaner = Cleaner.create();
Resource resource = new Resource();
cleaner.register(resource, new ResourceHandler(resource));

Example

Below is an example of using the Cleaner API in JDBC:

import java.lang.ref.Cleaner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class JdbcCleanerExample {
    private static final Cleaner cleaner = Cleaner.create();    
    public static void main(String[] args) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "user", "pass");
        System.out.println("Connection established......");
        CleanableConnection cleanableConn = new CleanableConnection(conn);        
        Statement stmt = cleanableConn.getConnection().createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM table");        
        while (rs.next()) {
            System.out.print(rs.getInt("ID")+", ");
            System.out.print(rs.getString("First_Name")+", ");
            System.out.print(rs.getString("Last_Name")+", ");
            System.out.print(rs.getDate("Date_Of_Birth")+", ");
            System.out.print(rs.getString("Place_Of_Birth")+", ");
            System.out.print(rs.getString("Country"));
            System.out.println();
        }
    }    
    static class CleanableConnection {
        private final Connection connection;
        private final Cleaner.Cleanable cleanable;        
        public CleanableConnection(Connection connection) {
            this.connection = connection;
            this.cleanable = cleaner.register(this, () -> {
                try {
                    if (!connection.isClosed()) {
                        connection.close();
                        System.out.println("Connection cleaned");
                    }
                } catch (Exception e) {
                    System.out.println("Cleanup error: " + e.getMessage());
                }
            });
        }        
        public Connection getConnection() {
            return connection;
        }
    }
}

Output

Connection established......
1, Shikhar, Dhawan, 1981-12-05, Delhi, India
2, Jonathan, Trott, 1981-04-22, CapeTown, SouthAfrica
3, Kumara, Sangakkara, 1977-10-27, Matale, Srilanka
4, Virat, Kohli, 1988-11-05, Mumbai, India
5, Rohit, Sharma, 1987-04-30, Nagpur, India
6, Ravindra, Jadeja, 1988-12-06, Nagpur, India
7, James, Anderson, 1982-06-30, Burnely, England
8, Ryan, McLaren, 1983-02-09, Kumberly, null
Connection cleaned
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-05-02T19:26:12+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements