您的位置:首页 > 其它

ThreadLocal解析

2015-11-07 17:08 363 查看
1、ThreadLocal解决了什么问题?

答:同线程内数据传参的问题,在开发中有时我们想将某一对象的引用在同一线程中多处使用,大家都知道在Thread类中,是有map的,也就是说每个Thread都有自己的context,查看下Thread源码:

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


我们大可通过此 map来将我们自己的对象设置在其中,但是我们也不得不每次获取当前Thread对象,然后从当前线程对象中获取map,然后为对象取定一个key值,把对象做为value放置在其中,这在代码上太麻烦了,如果我们有一个工具类就好了,因此ThreadLocal诞生了。记住,它仅仅只是一个工具类罢了,并没有起到实质性的作用,有了它我们的代码将变的简介。

至于很多同学理解的它能解决同一对象的多线程并发访问问题,那纯属扯淡!

2、ThreadLocal如何帮我们将对象放置在Thread的threadLocals中的?

废话少说,直接贴出JDK源码:

/**
* 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);
}

我们看到先获取当前线程对象,然后获取map,然后将threadlocal对象本身做为key,目标对象做为value设置进入map就ok了,如此简单
至于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();
}
整个set的过程其实就是一个数组实现hash算法的过程,对value值并没有做clone动作,这点很重要,这也意味着同一对象实质上可被多个Thread对象引用,并没有做到本质上的ThreadLocal。
也就是说,当你想要将对象设置进入Thread中的map中时,你需要先有一个对应的threadlocal对象。两个线程使用两个threadlocal对象对同一个对象(如:person对象)管理也是ok的,此时两个线程共享该对象。

想要获取刚刚设置的对象时,调用threadlocal对象的get()方法即可,以下是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();
}

以this为key获取对象

3、警告

多个线程仍然可以通过不同的treadlocal对象将同一个对象(如Person对象)设置在不同Thread的map中,此时多个线程共享该person对象。ThreadLocal只是一个工具而已。

4、实例

package com.wanyonghui.learn;

public class ThreadLocalLearn {

private static ThreadLocal<Person> tl = new ThreadLocal<Person>();

public static void func(){

Person p2 = (Person)tl.get();

System.out.println(p2.getName());
}

public static void main(String[] args) {

Person p = new Person();
p.setName("wanyonghui");
tl.set(p);

func();

Thread t = new Thread();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ThreadLocal 解析