线程局部变量(ThreadLocal)

一般情况下,我们将一个线程中的局部变量保存在线程之中。本文以装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回收。

 

转载于:https://my.oschina.net/u/2324558/blog/387688

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值