码迷,mamicode.com
首页 > 编程语言 > 详细

线程局部变量(ThreadLocal)

时间:2015-03-17 08:14:30      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

一般情况下,我们将一个线程中的局部变量保存在线程之中。本文以装Connection为例子。做法如下:

第一步:

private static ThreadLocal<Connection> tl;

第二步:

public static Connection getConnection() {
      Connection con = tl.get();
     if (con == null) {
     try {
         con = ds.getConnection();

         tl.set(con);

         } catch (Exception e) {
           throw new RuntimeException(e);
          }
  }

    return con;

 }

这样我们在处理事务时就会有使用同一对象,或者变量。

那我们来看下源码是这些方法是怎么实现的呢?

1、首先我们先看下源码:

 /**
     * 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);// 在这个进一步查看源码时,会看到其实就是MAP对象。以当前的t为key
        if (map != null)    
            map.set(this, value);
        else
            createMap(t, value);
    }

   也就是说上面的代码,是将数据装在MAP里面、

那么我们在来看下get()方法是怎么实现的呢?

2、get()

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

相信大家看到了这里应该就明白了吧,数据就是这么放的,今后我们在解决一些处理事务的时候,可以拥这个来解决、

每个thread中都存在一个map,map的类型是ThreadLocal,ThreadLocalMap,Map中的key为一个threadlocal实例。这个map的也使用了弱引用。不过弱引用是针对key,每个key都弱引用指向threadlocal,当我们指向的为空,就会被gc回收。

 

线程局部变量(ThreadLocal)

标签:

原文地址:http://my.oschina.net/u/2324558/blog/387688

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!