Spring 对hibernate事务处理的实现过程(辅助) ThreadLocal

来源:互联网 发布:js实现dos窗口效果 编辑:程序博客网 时间:2024/05/22 13:17

spring在事物处理的时候,会把ConnectionHolder和SessionHolder与线程绑定,使用的是ThreadLocal,下面看看ThreadLocal的实现是怎样做到线程间隔离的


先看看ThreadLocal 的几个主要方法

1 get方法

/**     * Returns the value in the current thread's copy of this     * thread-local variable.  If the variable has no value for the     * current thread, it is first initialized to the value returned     * by an invocation of the {@link #initialValue} method.     *     * @return the current thread's value of this thread-local     */    public T get() {        Thread t = Thread.currentThread(); // 获取当前线程        ThreadLocalMap map = getMap(t);  //获取当前线程的threadLocals  实际是ThreadLocal 的内部类ThreadLocal.ThreadLocalMap        if (map != null) {            ThreadLocalMap.Entry e = map.getEntry(this);  // 从当前线程的threadLocals中取出对象,使用的key是当前的ThreadLocal实例            if (e != null) {                @SuppressWarnings("unchecked")                T result = (T)e.value;                return result;            }        }        return setInitialValue();  // 如果当前线程的threadLocals还没有初始化,则初始化    }

2setInitialValue 方法

/**     * Variant of set() to establish initialValue. Used instead     * of set() in case user has overridden the set() method.     *     * @return the initial value     */    private T setInitialValue() {        T value = initialValue();   //初始值,默认返回null,可以根据需要重写实现        Thread t = Thread.currentThread();        ThreadLocalMap map = getMap(t);   // 根据初始值创建<span style="font-family: Arial, Helvetica, sans-serif;">ThreadLocal.ThreadLocalMap实例</span>        if (map != null)            map.set(this, value);        else            createMap(t, value);        return value;    }


3set方法

/**     * Sets the current thread's copy of this thread-local variable     * to the specified value.  Most subclasses will have no need to     * override this method, relying solely on the {@link #initialValue}     * method to set the values of thread-locals.     *     * @param value the value to be stored in the current thread's copy of     *        this thread-local.     */    public void set(T value) {        Thread t = Thread.currentThread();        ThreadLocalMap map = getMap(t);        if (map != null)            map.set(this, value);        else            createMap(t, value);    }


通过上面可以看出,get ,set 方法操作的map都是在当前线程中,所以效果是当前线程的本地变量,不同的线程之间不会操作到相互的实例。实际的保存变量的map是在Thread对象中

/* ThreadLocal values pertaining to this thread. This map is maintained     * by the ThreadLocal class. */    ThreadLocal.ThreadLocalMap threadLocals = null;




0 0
原创粉丝点击