When we learn JDBC, we use Connection, SqlSession, inputStream and other objects to complete the operation of the database. After using the resource, we must call a bunch of resources in Finally. So is there a better way?

/ / pseudo code
SqlSession sqlSession = sqlSessionFactory.openSession()
try  {
    / /...
}finally{
 sqlSession.close();
}
Copy the code

Here I will introduce a simple and quick way to automatically release resources.

Try statements have been enhanced in Java 7 since jdk1.7. It allows the try keyword to be followed by a pair of parentheses that declare and initialize one or more resources that must be closed at the end of the program (such as database connections, network connections, etc.). The try statement closes these resources automatically when the statement ends. This is called a try-with-resources statement.

/ / pseudo code
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
    / /...
}
Copy the code

In this case, the sqlSession is automatically closed after execution. We don’t have to close it in finally, so why does this automatically close the resource? Can all resources be shut down like this?

For classes that implement the Closeable or AutoCloseable interface, when you declare an instance of the class in a try(), after the try ends, The close method is called for example Sqlsession which is extends Closeable, extends AutoCloseable for almost any resource other than Sqlsession, OutputStream, BufferedReader, PrintStream, InputStream, whatever. So far, it is said that only JavaMail Transport objects cannot be automatically shut down in this way.

Note: If there are two resources inside try(), separated by commas, the resources’ close methods are called in the reverse order in which they were created. Try statements with resources can have catch and finally blocks just like regular try statements. In try-with-resources statements, any catch or finally block is executed only after the declared resource has been closed.

conclusion

  1. For classes that implement Closeable or AutoCloseable interfaces, the close method is called when a try() is declared.

  2. The close method that is automatically called after a try, before the method in finally is called.

  3. The close method is called on instances of try() regardless of whether an exception is raised (int I =1/0 throws an exception).

  4. The later an object is declared, the sooner it will be closed.