ThreadLocal的特点是每一个线程对应的对象都只与当前线程有关,当在全局声明一个使用了ThreadLocal的对象时,在每个线程调用它时,都会有一个自己线程对应的拷贝,而赋值则是由
def initialValue() 或set方法来完成的
我们要实现了一个Protocol层,它内部会保留一个socket连接
class ThreadLocalProtocol { val protocol = new ThreadLocal[ZTMultiplexedProtocol]() { override def initialValue(): ZTMultiplexedProtocol = { val zmp = ZLineStatusClient.getZmp zmp.openTTransport() zmp } } def getProtocol(): ZTMultiplexedProtocol = { protocol.get() } }
我们在主线程进行
lazy val threadLocalProtocol = new ThreadLocalProtocol
这里用不用lazy应该是一样的,因为ThreadLocal.get()调用时,才会延迟加载对象,这里是ZTMultiplexedProtocol,我们来看看jdk源码
/** * 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); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); }
如果map里面已经有对象了,就返回其值,这里进行了一次强制类型转换,否则调用setInitialValue(),我们再来看看
/** * 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(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); return value; }
setInitialValue()方法其实也是对map的操作,那么这个名字叫map的东西到底是什么呢?我们先来看看getMap(t)是什么东西
/** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
Thread.threadLocals返回的就是ThreadLocalMap,由于Thread.currentThread()方法是native的,不得而知他是怎么初始化threadLocals变量的,根据map.set方法的代码
/** * Set the value associated with key. * * @param key the thread local object * @param value the value to be set */ private void set(ThreadLocal key, Object value) { // We don't use a fast path as with get() because it is at // least as common to use set() to create new entries as // it is to replace existing ones, in which case, a fast // path would fail more often than not. Entry[] tab = table; int len = tab.length; int i = key.threadLocalHashCode & (len-1); for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { ThreadLocal k = e.get(); if (k == key) { e.value = value; return; } if (k == null) { replaceStaleEntry(key, value, i); return; } } tab[i] = new Entry(key, value); int sz = ++size; if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); }
我们所声明的threadLocalProtocol对象,在每个线程set值时,用的是该线程的ThreadLocalMap,这个map可以维护多个不同的ThreadLocal对象,也就是一对多,比如这样:
lazy val threadLocalProtocol1 = new ThreadLocalProtocol lazy val threadLocalProtocol2 = new ThreadLocalProtocol lazy val threadLocalProtocol3 = new ThreadLocalProtocol
在每个线程里面调用threadLocalProtocol.getProtocol()触发ThreadLocal对象内部的get()方法,然后Thread.currentThread().threadLocals对象就维护了3个ZTMultiplexedProtocol
,这里就不细说ThreadLocalMap的数据结构了,它内部采用了WeakReference,这点可能是出于效率来考虑的。
总之,在你多线程中调用set(),get()方法是,他们都是对于当前线程而言的,和其他线程没有关系了
这个功能在多线程中进行类似建立socketConnection时,相当有用
但是我们还有疑虑,何不在每个线程中直接 new 一个ZTMultiplexedProtocol呢?
试想一下,我们的代码是不是有那么简单的逻辑,可以在run()方法中直接使用ZTMultiplexedProtocol,或者只有在run()中才需要ZTMultiplexedProtocol呢,这一点非常重要,加入ZTMultiplexedProtocol的对象需要被传来传去,是不是我们要在每个方法上都加上参数(zmp:ZTMultiplexedProtocol)呢,这个就好不麻烦了,如果有以下一个解决办法,岂不是简洁明朗多了:
Object G{ private class ThreadLocalProtocol { val protocol = new ThreadLocal[ZTMultiplexedProtocol]() { override def initialValue(): ZTMultiplexedProtocol = { val zmp = ZLineStatusClient.getZmp zmp.openTTransport() zmp } } def getProtocol(): ZTMultiplexedProtocol = { protocol.get() } } val hreadLocalProtocol = new ThreadLocalProtocol }
每个需要这个ZTMultiplexedProtocol的地方,我们只需要这样获得
G.hreadLocalProtocol.getProtocol()
这样,无论在哪里都可以通过一个全局的对象直接获得ZTMultiplexedProtocol了,避免了代码的冗长,方法的不健康(比如,它完成的任务只是依赖了ZTMultiplexedProtocol,甚至都可能不会使用,我们也需要在它的父接口中声明这个参数)
ThreadLocal用在连接池技术中也未尝不可,只要我们保证线程数不会疯涨,而是控制在一个线程池中的,我们用ThreadLocal这样的方式也是安全的
01-29记
最近头晕乎乎的,想到了线程池与ThreadLocal的问题,还特意又看了线程池的代码,也没有发现对ThreadLocal的特殊照顾。基于此,想到了线程池线程复用时,web开发时,不要以为每个线程都是一个新的ThreadLocal变量,当然对于使用ThreadLocal来存储jdbc connection的spring 事务框架,这又是一个好事,自然而然达到了连接复用的功能