mybatis_13_SqlSessionFactory的DCL单例模式

SqlSessionFactory的DCL单例模式

 

public class SqlSessionFactorySingleton {
    private SqlSessionFactorySingleton(){

    }
    /**
     * volatile关键字在此处的作用是:
     * 1.线程的可见性:当一个线程修改一个共享变量时,另外一个线程能读到这个修改的值;
     * 2.顺序一致性:禁止指令重排序
     */
    private static volatile SqlSessionFactory sqlSessionFactory = null;
    public static SqlSessionFactory getInstance() throws IOException {
        //双检锁/双重校验锁 DCL(double-checked locking)
        if(sqlSessionFactory == null){
            /**
            synchronized关键字是一种同步锁,当一个线程访问对象中的synchronized同步代码块时,
             其他试图访问该对象的线程将被阻塞
             */
            synchronized (SqlSessionFactorySingleton.class){
                if(sqlSessionFactory == null){
                    String resource = "mybatis-config2.xml";
                    InputStream inputStream = Resources.getResourceAsStream(resource);
                    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                    
                }
            }
        }
        return sqlSessionFactory;
    }
}

  创建SqlSessionFactory实例:

SqlSessionFactory sqlSessionFactory = SqlSessionFactorySingleton.getInstance();

 

posted @ 2022-08-30 17:05  留白*  阅读(62)  评论(0编辑  收藏  举报