结合ThreadLocal来看spring事务源码,感觉下清泉般的洗涤!

前言

  在个人博客spring事务源码解析中,提到了一个很关键的点:将connection绑定到当前线程来保证这个线程中的数据库操做用的是同一个connection。可是没有细致的讲到如何绑定,以及为何这么绑定;另外也没有讲到链接池的相关问题:如何从链接池获取,如何归还链接到链接池等等。那么下面就请听我慢慢道来。html

  路漫漫其修远兮,吾将上下而求索!git

  github:https://github.com/youzhibinggithub

  码云(gitee):https://gitee.com/youzhibingspring

ThreadLocal

  讲spring事务以前,咱们先来看看ThreadLocal,它在spring事务中是占据着比较重要的地位;无论你对ThreadLocal熟悉与否,且都静下心来听我唐僧般的念叨。数据库

  先强调一点:ThreadLocal不是用来解决共享变量问题的,它与多线程的并发问题没有任何关系编程

  基本介绍

    当使用ThreadLocal维护变量时,ThreadLocal为每一个使用该变量的线程提供独立的变量副本,因此每个线程均可以独立地改变本身的副本,而不会影响其它线程所对应的副本,以下例:数组

public class ThreadLocalTest
{
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
    ThreadLocal<String> stringLocal = new ThreadLocal<String>();
    
    public void set()
    {
        longLocal.set(1L);
        stringLocal.set(Thread.currentThread().getName());
    }
    
    public long getLong()
    {
        return longLocal.get();
    }
    
    public String getString()
    {
        return stringLocal.get();
    }
    
    public static void main(String[] args) throws InterruptedException
    {
        final ThreadLocalTest test = new ThreadLocalTest();
        
        test.set();     // 初始化ThreadLocal
        for (int i=0; i<10; i++)
        {
            System.out.println(test.getString() + " : " + test.getLong() + i);
        }
        
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                for (int i=0; i<10; i++)
                {
                    System.out.println(test.getString() + " : " + test.getLong() + i);
                }
            };
        };
        thread1.start();
        
        Thread thread2 = new Thread(){
            public void run() {
                test.set();
                for (int i=0; i<10; i++)
                {
                    System.out.println(test.getString() + " : " + test.getLong() + i);
                }
            };
        };
        thread2.start();
    }
}

    执行结果以下session

    能够看到,各个线程的longLocal值与stringLocal值是相互独立的,本线程的累加操做不会影响到其余线程的值,真正达到了线程内部隔离的效果。多线程

  源码解读

    这里我就不进行ThreadLocal的源码解析,建议你们去看我参考的博客,我的认为看那两篇博客就能对ThreadLocal有个很深地认知了。并发

    作个重复的强调(引用[Java并发包学习七]解密ThreadLocal中的一段话):

Thread与ThreadLocal对象之间的引用关系图
 
看了ThreadLocal源码,不知道你们有没有一个疑惑:为何像上图那么设计? 若是给你设计,你会怎么设计?相信大部分人会有这样的想法,我也是这样的想法:
  ”每一个ThreadLocal类建立一个Map,而后用线程的ID做为Map的key,实例对象做为Map的value,这样就能达到各个线程的值隔离的效果“
JDK最先期的ThreadLocal就是这样设计的。(不肯定是不是1.3)以后ThreadLocal的设计换了一种方式,也就是目前的方式,那有什么优点了:
  一、这样设计以后每一个Map的Entry数量变小了:以前是Thread的数量,如今是ThreadLocal的数量,能提升性能,听说性能的提高不是一点两点(没有亲测)
  二、当Thread销毁以后对应的ThreadLocalMap也就随之销毁了,能减小内存使用量。

Spring事务中的ThreadLocal

  最多见的ThreadLocal使用场景为 用来解决数据库链接、Session管理等,那么接下来咱们就看看spring事务中ThreadLocal的应用

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");
DaoImpl daoImpl = (DaoImpl) ac.getBean("daoImpl");
System.out.println(daoImpl.insertUser("yes", 25));

  只要某个类的方法、类或者接口上有事务配置,spring就会对该类的实例生成代理。因此daoImpl是DaoImpl实例的代理实例的引用,而不是DaoImpl的实例(目标实例)的引用;当咱们调用目标实例的方法时,实际调用的是代理实例对应的方法,若目标方法没有被@Transactional(或aop注解,固然这里不涉及aop)修饰,那么代理方法直接反射调用目标方法,若目标方法被@Transactional修饰,那么代理方法会先执行加强(例如判断当前线程是否存在connection,不存在则新建并绑定到当前线程等等),而后经过反射执行目标方法,最后回到代理方法执行加强(例如,事务回滚或事务提交、connection归还到链接池等等处理)。这里的绑定connection到当前线程就用到了ThreadLocal,咱们来看看源码

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
    Connection con = null;

    try {
        
        if (txObject.getConnectionHolder() == null ||
                txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
            // 从链接池获取一个connection
            Connection newCon = this.dataSource.getConnection();
            if (logger.isDebugEnabled()) {
                logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
            }
            // 包装newCon,并赋值到txObject,并标记是新的ConnectionHolder
            txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
        }

        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con = txObject.getConnectionHolder().getConnection();

        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);

        // Switch to manual commit if necessary. This is very expensive in some JDBC drivers,
        // so we don't want to do it unnecessarily (for example if we've explicitly
        // configured the connection pool to set it already).
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        txObject.getConnectionHolder().setTransactionActive(true);

        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }

        // 如果新的ConnectionHolder,则将它绑定到当前线程中
        // Bind the session holder to the thread.
        if (txObject.isNewConnectionHolder()) {
            TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
        }
    }

    catch (Throwable ex) {
        if (txObject.isNewConnectionHolder()) {
            DataSourceUtils.releaseConnection(con, this.dataSource);
            txObject.setConnectionHolder(null, false);
        }
        throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
    }
}
/**
 * Bind the given resource for the given key to the current thread.
 * @param key the key to bind the value to (usually the resource factory)
 * @param value the value to bind (usually the active resource object)
 * @throws IllegalStateException if there is already a value bound to the thread
 * @see ResourceTransactionManager#getResourceFactory()
 */
public static void bindResource(Object key, Object value) throws IllegalStateException {        //key:一般指资源工厂,也就是connection工厂,value:一般指活动的资源,也就是活动的ConnectionHolder
    
    // 必要时unwrap给定的链接池; 不然按原样返回给定的链接池。
    Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
    Assert.notNull(value, "Value must not be null");
    Map<Object, Object> map = resources.get();
    // set ThreadLocal Map if none found   若是ThreadLocal Map不存在则新建,并将其设置到resources中
    // private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<Map<Object, Object>>("Transactional resources");
  // 这就到了ThreadLocal流程了 if (map == null) { map = new HashMap<Object, Object>(); resources.set(map); } Object oldValue = map.put(actualKey, value); // Transparently suppress a ResourceHolder that was marked as void... if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) { oldValue = null; } if (oldValue != null) { throw new IllegalStateException("Already value [" + oldValue + "] for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]"); } if (logger.isTraceEnabled()) { logger.trace("Bound value [" + value + "] for key [" + actualKey + "] to thread [" + Thread.currentThread().getName() + "]"); } }

总结

  一、ThreadLocal能解决的问题,那确定不是共享变量(多线程并发)问题,只是看起来有些像并发;像火车票、电影票这样的真正的共享变量的问题用ThreadLocal是解决不了的,同一时间,同一趟车的同一个座位,你敢用ThreadLocal来解决吗?

  二、每一个Thread维护一个ThreadLocalMap映射表,这个映射表的key是ThreadLocal实例自己,value是真正须要存储的Object

  三、druid链接池用的是数组来存放的connectionHolder,不是我认为的list,connectionHolder从线程中解绑后,归还到数组链接池中;connectionHolder是connection的封装

疑问

  private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<Map<Object, Object>>("Transactional resources");

  一、 为何是ThreadLocal<Map<Object, Object>>,而不是ThreadLocal<ConnectionHolder>

  二、 ThreadLocal<Map<Object, Object>> 中的Map的key是为何是DataSource

  望知道的朋友赐教下,评论留言或者私信均可以,谢谢!

参考

  [Java并发包学习七]解密ThreadLocal

  Java并发编程:深刻剖析ThreadLocal

相关文章
相关标签/搜索