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();
}
}
答:同线程内数据传参的问题,在开发中有时我们想将某一对象的引用在同一线程中多处使用,大家都知道在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();
}
}
相关文章推荐
- DVI 视频接口图文解析
- IE6不能正常解析CSS文件问题的解决方法及原因分析
- C#自写的一个HTML解析类(类似XElement语法)
- ruby 过程对象 解析
- C#域名解析简单实现方法
- ruby 类常量 解析
- PHP抓取网页、解析HTML常用的方法总结
- 一些javascript一些题目的解析
- Javascript URI 解析介绍
- 解析映像劫持技术第1/3页
- 解析 ruby 全局变量
- php中使用parse_url()对网址进行解析的实现代码(parse_url详解)
- js解析xml字符串和xml文档实现原理及代码(针对ie与火狐)
- jquery JSON的解析方式
- 什么是eclipse,eclipse的意思解析
- 动态webservice调用接口并读取解析返回结果
- 使用jquery解析XML示例代码
- 比较详细的关于javascript 解析json的代码
- JavaScript 解析Json字符串的性能比较分析代码
- JSON解析和XML解析区别对比