threadlocal是在多线程环境下经常使用的一个类。
这个类并不是为了解决多线程间共享变量的问题。举个例子,在一个电商系统中,用一个long型变量表示某个商品的库存量,多个线程需要访问库存量进行销售,并减去销售数量,以更新库存量。在这个场景中,是不能使用threadlocal类的。
threadlocal适用的场景是,多个线程都需要使用一个变量,但这个变量的值不需要在各个线程间共享,各个线程都只使用自己的这个变量的值。这样的场景下,可以使用threadlocal。此外,我们使用threadlocal还能解决一个参数过多的问题。例如一个线程内的某个方法f1有10个参数,而f1调用f2时,f2又有10个参数,这么多的参数传递十分繁琐。那么,我们可以使用threadlocal来减少参数的传递,用threadlocal定义全局变量,各个线程需要参数时,去全局变量去取就可以了。
接下来我们看一下threadlocal的源码。首先是类的介绍。如下图。这个类提供了线程本地变量。这些变量使每个线程都有自己的一份拷贝。threadlocal期望能够管理一个线程的状态,例如用户id或事务id。例如下面的例子产生线程本地的唯一id。线程的id是第一次调用时进行复制,并且在后面的调用中保持不变。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
this class provides thread-local variables.
these variables differ from their normal counterparts in that each thread that accesses
one (via its get or set method) has its own, independently initialized copy of the variable. threadlocal instances are typically private static fields in classes that
wish to associate state with a thread (e.g., a user id or transaction id).
for example, the class below generates unique identifiers local to each thread.
a thread's id is assigned the first time it invokes threadid.get() and
remains unchanged on subsequent calls.
import java.util.concurrent.atomic.atomicinteger;
public class threadid {
// atomic integer containing the next thread id to be assigned
private static final atomicinteger nextid = new atomicinteger( 0 );
// thread local variable containing each thread's id
private static final threadlocal<integer> threadid =
new threadlocal<integer>() {
@override protected integer initialvalue() {
return nextid.getandincrement();
}
};
// returns the current thread's unique id, assigning it if necessary
public static int get() {
return threadid.get();
}
}
each thread holds an implicit reference to its copy of a thread-local
variable as long as the thread is alive and the threadlocal instance is
accessible; after a thread goes away, all of its copies of thread-local
instances are subject to garbage collection (unless other references to
these copies exist).
|
下面看一下set方法。
set方法的作用是,把线程本地变量的当前线程的拷贝设置为指定的值。大部分子类无需重写该方法。首先获取当前线程,然后获取当前线程的threadlocalmap。如果threadlocalmap不为null,则设置当前线程的值为指定的值,否则调用createmap方法。
获取线程的threadlocalmap对象,是直接返回的线程的threadlocals,类型为threadlocalmap。也就是说,每个线程都有一个threadlocalmap对象,用于保存该线程关联的所有的threadlocal类型的变量。threadlocalmap的key是threadlocal,value是该threadlocal对应的值。具体什么意思呢?在程序中,我们可以定义不止一个threadlocal对象,一般会有多个,比如定义3个threadlocal<string>,再定义2个threadlocal<integer>,而每个线程可能都需要访问全部这些threadlocal的变量,那么,我们用什么数据结构来实现呢?当然,最好的方式就是像源码中的这样,每个线程有一个threadlocalmap,key为threadlocal变量名,而value为该线程在该threadlocal变量的值。这个设计实在是太巧妙了。
写到这里,自己回想起之前换工作面试时,面试官问自己关于threadlocal的实现原理。那个时候,为了准备面试,自己只在网上看了一些面试题,并没有真正掌握,在回答这个问题时,我有印象,自己回答的是用一个map,线程的id值作为key,变量值作为value,诶,露馅了啊。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
/**
* 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);
}
/**
* 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;
}
/**
* create the map associated with a threadlocal. overridden in
* inheritablethreadlocal.
* @param t the current thread
* @param firstvalue value for the initial entry of the map
**/
void createmap(thread t, t firstvalue) {
t.threadlocals = new threadlocalmap( this , firstvalue);
}
|
接下来看一下get方法。
源码如下。首先获取当前线程的threadlocalmap,然后,从threadlocalmap获取该threadlocal变量对应的value,然后返回value。如果threadlocalmap为null,则说明该线程还没有设置该threadlocal变量的值,那么就返回setinitialvalue方法的返回值。其中的initialvalue方法的返回值,通常情况下为null。但是,子类可以重写initialvalue方法以返回期望的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
/**
* 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 ) {
@suppresswarnings ( "unchecked" )
t result = (t)e.value;
return result;
}
}
return 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;
}
protected t initialvalue() {
return null ;
}
|
文章的最后,简单介绍一下threadlocalmap这个类,该类是threadlocal的静态内部类。它对hashmap进行了改造,用于保存各个threadlocal变量和某线程的该变量的值的映射关系。每个线程都有一个threadlocalmap类型的属性。threadlocalmap中的table数组的长度,与该线程访问的threadlocal类型变量的个数有关,而与别的无关。
this is the end。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/li_canhui/article/details/85231116