x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Java Autocloseable try-with-resources

    Java try-with-resources was introduced with Java 7. Using try-with-resources, you can get rid of resource clean up in finally block. For example if you use try-with-resources, you no longer need to add finally block to close a BufferedReader.

    1) try-with-resources in java 7, example of BufferedReader

    • Note that in below example closing of resources (BufferedReader) is not required in finally block. When the try block finishes the BufferedReader will be closed automatically. In earlier versions of Java before JDK 1.7, the was done using the finally block.
    • Above is possible because BufferedReader implements the Java interface java.lang.AutoCloseable. All classes implementing this interface can be used inside the try-with-resources construct.

    Before Java 7

    	
    // Before Java 7, you had to close BufferedReader manually in finally block.
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class MyClass {
        public static void main(String[] args) {
            String filePath = "C://File.txt";  
            BufferedReader br = null;
            try {
                br =  new BufferedReader(new FileReader(filePath)); 
                String s; 
                while ((s = br.readLine()) != null) {
                    System.out.println(s); 
                } 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } finally {
                try {
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }          
        }
    }

    try-with-resources in Java 7

    /*In Java 7, with try-with-resources, BufferedReader will be closed automatically after try block. */
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class MyClass {
        public static void main(String[] args) {
            String filePath = "C://File.txt";  
            // try-with-resources statement is logically calling a finally block to close the reader.
            try (BufferedReader b = new BufferedReader(new FileReader(filePath))) {
                String s; 
                while ((s = b.readLine()) != null) {
                    System.out.println(s); 
                } 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
            // BufferedReader will be closed automatically        
        }
    }    

    2) try with multiple resources in java, example of JDBC Connection & PreparedStatement

    • Note that in below example closing of resources (Connection & PreparedStatement) is not required in finally block. When the try block finishes the Connection & PreparedStatement will be closed automatically. In earlier versions of Java before JDK 1.7, the was done using the finally block.
    • Above is possible because Connection & PreparedStatement implement the Java interface java.lang.AutoCloseable. All classes implementing this interface can be used inside the try-with-resources construct.

    Before Java 7

    
    // Before Java 7, you had to close Connection & PreparedStatement manually in finally block.
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class MyClass {
        public static void main(String[] args) {
            Connection connection = null;
            PreparedStatement  ps  = null;
            String url, user, pwd; 
            
            try {
                connection = DriverManager.getConnection(url, user, pwd);
                ps = connection.prepareStatement("SELECT UnitPrice from Book WHERE Title LIKE ?");
                ps.setString(1, "%Java%");
                ResultSet rs = ps.executeQuery();
                // ... process the results
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } finally {
                try {
                    if (ps != null) {
                        ps.close();
                    }
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }     
                   
        }
        
    }
    
    

    try with multiple resources in Java 7

    /*In Java 7, with try with resources, Connection & PreparedStatement will be closed automatically after try block. */
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class MyClass {
        public static void main(String[] args) {
            Connection connection = null;
            PreparedStatement  ps  = null;
            String url, user, pwd; 
            
            try {
                connection = DriverManager.getConnection(url, user, pwd);
                ps = connection.prepareStatement("SELECT UnitPrice from Book WHERE Title LIKE ?");
                ps.setString(1, "%Java%");
                ResultSet rs = ps.executeQuery();
                // ... process the results
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
            // Connection & PreparedStatement will be closed automatically         
        }
    }    

    3) Usual try block

    The actual try block still works the same way, i.e. if you don't use try-with-resources, you still need catch or finally block. Below code will not work.

    try {
        // access a file
    }    

    4) Implementing AutoCloseable interface

    You can't instantiate any Class inside try-with-resources, for example below code will not compile.

    try (String str = new String("")) {
    }    

    If you want to perform code cleanup for your class, then that class must implement AutoCloseable interface as shown below. AutoCloseable interface has only one method close() which throws Exception. Any resource cleaup should be performed inside this method.

    public class MyResource implements AutoCloseable {
    	
        public void print() {
            System.out.println("print called");
        }
    	
        @Override
        public void close() throws Exception {
            System.out.println("closed");
        }
    	
        public static void main(String[] args) {
            try (MyResource myResource = new MyResource()) {
                myResource.print();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }  

    Output :

    print called
    closed
    


    References : https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This