try(){} automatically release resources

Original background and practice

Improve 

Description


 

Original background and practice

When we use resources, we must close the resources. For example, when using jdbc connection or inputStream, we must close the resources in finally.

For example, when obtaining the SqlSession of the Mybatis framework 

package com.dao;

import com.lingaolu.dao.DeptDao;
import com.lingaolu.pojo.Dept;
import com.lingaolu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @author 林高禄
 * @create 2020-10-12-9:56
 */
public class DeptDaoTest {

    @Test
    public void getDeptList(){
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            DeptDao mapper = sqlSession.getMapper(DeptDao.class);
            List<Dept> deptList = mapper.getDeptList();
            deptList.forEach(System.out::println);
        }catch (Exception e){

        }finally {
           if(null != sqlSession){
               sqlSession.close();
           }
        }

    }
}

 

But this is very troublesome to write, and sometimes we forget to close the resource. So is there a better way?

Improve 

 The Java version I use is 1.8, and there are also hints here

 

Starting from jdk1.7, Java 7 has enhanced the function of the try statement-it allows a pair of parentheses to be followed by the try keyword. The parentheses can declare and initialize one or more resources. The resources here refer to those that must be in Resources that must be closed at the end of the program (such as database connections, network connections, etc.), the try statement automatically closes these resources at the end of the statement. This is called a try-with-resources statement.

Look at the official website of Mybatis, also used this approach

So we changed the code to this way

package com.dao;

import com.lingaolu.dao.DeptDao;
import com.lingaolu.pojo.Dept;
import com.lingaolu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @author 林高禄
 * @create 2020-10-12-9:56
 */
public class DeptDaoTest {

    @Test
    public void getDeptList(){
        try(SqlSession sqlSession = MybatisUtils.getSqlSession()){
            DeptDao mapper = sqlSession.getMapper(DeptDao.class);
            List<Dept> deptList = mapper.getDeptList();
            deptList.forEach(System.out::println);
        }
    }
}

 

In this case, sqlsession will be automatically closed after execution. We don't need to close it in finally, and we don't have to worry about forgetting to close it again. 

Description

So why can resources be automatically closed in this way? Can all resources be closed like this?

In fact, as long as these resource implementation classes implement the Closeable or AutoCloseable interface, they can be automatically closed. For example, Sqlsession is extends Closeable, Closeable extends AutoCloseable.

We see that SqlSession implements the Closeable interface

Almost all resources can be automatically closed in this way, such asOutputStream,BufferedReader,PrintStream,InputStream等,都可以。据说到目前为止,只有JavaMail Transport对象不能利用这种方式实现自动关闭。

note:

  • If there are two resources in try(), separated by commas, the call order of the close method of the resources is opposite to the order in which they were created.
  • A try statement with resources can have catch and finally blocks like ordinary try statements. In the try-with-resources statement, any catch or finally block is executed after the declared resource is closed.

 

Guess you like

Origin blog.csdn.net/lgl782519197/article/details/109051343