ThreadLocal的特色是每个线程对应的对象都只与当前线程有关,当在全局声明一个使用了ThreadLocal的对象时,在每一个线程调用它时,都会有一个本身线程对应的拷贝,而赋值则是由java
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源码socket
/** * 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(),咱们再来看看ide
/** * 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)是什么东西this
/** * 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对象,也就是一对多,好比这样:scala
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,这点多是出于效率来考虑的。code
总之,在你多线程中调用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这样的方式也是安全的
本文出自 “沐浴心情” 博客,请务必保留此出处http://lj3331.blog.51cto.com/5679179/1353702