天天看点

正确理解ThreadLocal

首先,threadlocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过threadlocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。 

另外,说threadlocal使得各线程能够保持各自独立的一个对象,并不是通过threadlocal.set()来实现的,而是通过每个线程中的new 对象 的操作来创建的对象,每个线程创建一个,不是什么对象的拷贝或副本。通过threadlocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行threadlocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象,threadlocal实例是作为map的key来使用的。 

如果threadlocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的threadlocal.get()取得的还是这个共享对象本身,还是有并发访问问题。 

下面来看一个hibernate中典型的threadlocal的应用: 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<code>private</code> <code>static</code> <code>final</code> <code>threadlocal threadsession = </code><code>new</code> <code>threadlocal();  </code>

<code>  </code> 

<code>public</code> <code>static</code> <code>session getsession() </code><code>throws</code> <code>infrastructureexception {  </code>

<code>    </code><code>session s = (session) threadsession.get();  </code>

<code>    </code><code>try</code> <code>{  </code>

<code>        </code><code>if</code> <code>(s == </code><code>null</code><code>) {  </code>

<code>            </code><code>s = getsessionfactory().opensession();  </code>

<code>            </code><code>threadsession.set(s);  </code>

<code>        </code><code>}  </code>

<code>    </code><code>} </code><code>catch</code> <code>(hibernateexception ex) {  </code>

<code>        </code><code>throw</code> <code>new</code> <code>infrastructureexception(ex);  </code>

<code>    </code><code>}  </code>

<code>    </code><code>return</code> <code>s;  </code>

<code>}</code>

可以看到在getsession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionfactory().opensession()来创建一个session,再将session set到线程中,实际是放到当前线程的threadlocalmap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个threadlocalmap(下面会讲到),而threadsession作为这个值的key,要取得这个session可以通过threadsession.get()来得到,里面执行的操作实际是先取得当前线程中的threadlocalmap,然后将threadsession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。 

显然,其他线程中是取不到这个session的,他们也只能取到自己的threadlocalmap中的东西。要是session是多个线程共享使用的,那还不乱套了。 

试想如果不用threadlocal怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,threadlocal的实现刚好相反,它是在每个线程中有一个map,而将threadlocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。 

总之,threadlocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点: 

1。每个线程中都有一个自己的threadlocalmap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。 

2。将一个共用的threadlocal静态实例作为key,将不同对象的引用保存到不同线程的threadlocalmap中,然后在线程执行的各处通过这个静态threadlocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。 

当然如果要把本来线程共享的对象通过threadlocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。 

threadlocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。 

下面来看看threadlocal的实现原理(jdk1.5源码) 

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

<code>public</code> <code>class</code> <code>threadlocal&lt;t&gt; {  </code>

<code>    </code><code>/** </code>

<code>     </code><code>* threadlocals rely on per-thread hash maps attached to each thread </code>

<code>     </code><code>* (thread.threadlocals and inheritablethreadlocals).  the threadlocal </code>

<code>     </code><code>* objects act as keys, searched via threadlocalhashcode.  this is a </code>

<code>     </code><code>* custom hash code (useful only within threadlocalmaps) that eliminates </code>

<code>     </code><code>* collisions in the common case where consecutively constructed </code>

<code>     </code><code>* threadlocals are used by the same threads, while remaining well-behaved </code>

<code>     </code><code>* in less common cases. </code>

<code>     </code><code>*/</code>  

<code>    </code><code>private</code> <code>final</code> <code>int</code> <code>threadlocalhashcode = nexthashcode();  </code>

<code>     </code><code>* the next hash code to be given out. accessed only by like-named method. </code>

<code>    </code><code>private</code> <code>static</code> <code>int</code> <code>nexthashcode = </code><code>0</code><code>;  </code>

<code>     </code><code>* the difference between successively generated hash codes - turns </code>

<code>     </code><code>* implicit sequential thread-local ids into near-optimally spread </code>

<code>     </code><code>* multiplicative hash values for power-of-two-sized tables. </code>

<code>    </code><code>private</code> <code>static</code> <code>final</code> <code>int</code> <code>hash_increment = </code><code>0x61c88647</code><code>;  </code>

<code>     </code><code>* compute the next hash code. the static synchronization used here </code>

<code>     </code><code>* should not be a performance bottleneck. when threadlocals are </code>

<code>     </code><code>* generated in different threads at a fast enough rate to regularly </code>

<code>     </code><code>* contend on this lock, memory contention is by far a more serious </code>

<code>     </code><code>* problem than lock contention. </code>

<code>    </code><code>private</code> <code>static</code> <code>synchronized</code> <code>int</code> <code>nexthashcode() {  </code>

<code>        </code><code>int</code> <code>h = nexthashcode;  </code>

<code>        </code><code>nexthashcode = h + hash_increment;  </code>

<code>        </code><code>return</code> <code>h;  </code>

<code>     </code><code>* creates a thread local variable. </code>

<code>    </code><code>public</code> <code>threadlocal() {  </code>

<code>     </code><code>* returns the value in the current thread's copy of this thread-local </code>

<code>     </code><code>* variable.  creates and initializes the copy if this is the first time </code>

<code>     </code><code>* the thread has called this method. </code>

<code>     </code><code>* </code>

<code>     </code><code>* @return the current thread's value of this thread-local </code>

<code>    </code><code>public</code> <code>t get() {  </code>

<code>        </code><code>thread t = thread.currentthread();  </code>

<code>        </code><code>threadlocalmap map = getmap(t);  </code>

<code>        </code><code>if</code> <code>(map != </code><code>null</code><code>)  </code>

<code>            </code><code>return</code> <code>(t)map.get(</code><code>this</code><code>);  </code>

<code>        </code><code>// maps are constructed lazily.  if the map for this thread  </code>

<code>        </code><code>// doesn't exist, create it, with this threadlocal and its  </code>

<code>        </code><code>// initial value as its only entry.  </code>

<code>        </code><code>t value = initialvalue();  </code>

<code>        </code><code>createmap(t, value);  </code>

<code>        </code><code>return</code> <code>value;  </code>

<code>     </code><code>* sets the current thread's copy of this thread-local variable </code>

<code>     </code><code>* to the specified value.  many applications will have no need for </code>

<code>     </code><code>* this functionality, relying solely on the {@link #initialvalue} </code>

<code>     </code><code>* method to set the values of thread-locals. </code>

<code>     </code><code>* @param value the value to be stored in the current threads' copy of </code>

<code>     </code><code>*        this thread-local. </code>

<code>    </code><code>public</code> <code>void</code> <code>set(t value) {  </code>

<code>            </code><code>map.set(</code><code>this</code><code>, value);  </code>

<code>        </code><code>else</code>  

<code>            </code><code>createmap(t, value);  </code>

<code>     </code><code>* get the map associated with a threadlocal. overridden in </code>

<code>     </code><code>* inheritablethreadlocal. </code>

<code>     </code><code>* @param  t the current thread </code>

<code>     </code><code>* @return the map </code>

<code>    </code><code>threadlocalmap getmap(thread t) {  </code>

<code>        </code><code>return</code> <code>t.threadlocals;  </code>

<code>     </code><code>* create the map associated with a threadlocal. overridden in </code>

<code>     </code><code>* @param t the current thread </code>

<code>     </code><code>* @param firstvalue value for the initial entry of the map </code>

<code>     </code><code>* @param map the map to store. </code>

<code>    </code><code>void</code> <code>createmap(thread t, t firstvalue) {  </code>

<code>        </code><code>t.threadlocals = </code><code>new</code> <code>threadlocalmap(</code><code>this</code><code>, firstvalue);  </code>

<code>    </code><code>.......  </code>

<code>     </code><code>* threadlocalmap is a customized hash map suitable only for </code>

<code>     </code><code>* maintaining thread local values. no operations are exported </code>

<code>     </code><code>* outside of the threadlocal class. the class is package private to </code>

<code>     </code><code>* allow declaration of fields in class thread.  to help deal with </code>

<code>     </code><code>* very large and long-lived usages, the hash table entries use </code>

<code>     </code><code>* weakreferences for keys. however, since reference queues are not </code>

<code>     </code><code>* used, stale entries are guaranteed to be removed only when </code>

<code>     </code><code>* the table starts running out of space. </code>

<code>    </code><code>static</code> <code>class</code> <code>threadlocalmap {  </code>

<code>    </code><code>........  </code>

可以看到threadlocal类中的变量只有这3个int型: 

正确理解ThreadLocal

<code>private</code> <code>final</code> <code>int</code> <code>threadlocalhashcode = nexthashcode();  </code>

<code>private</code> <code>static</code> <code>int</code> <code>nexthashcode = </code><code>0</code><code>;  </code>

<code>private</code> <code>static</code> <code>final</code> <code>int</code> <code>hash_increment = </code><code>0x61c88647</code><code>;</code>

而作为threadlocal实例的变量只有 threadlocalhashcode 这一个,nexthashcode 和hash_increment 是threadlocal类的静态变量,实际上hash_increment是一个常量,表示了连续分配的两个threadlocal实例的threadlocalhashcode值的增量,而nexthashcode 的表示了即将分配的下一个threadlocal实例的threadlocalhashcode 的值。 

可以来看一下创建一个threadlocal实例即new threadlocal()时做了哪些操作,从上面看到构造函数threadlocal()里什么操作都没有,唯一的操作是这句: 

正确理解ThreadLocal

<code>private</code> <code>final</code> <code>int</code> <code>threadlocalhashcode = nexthashcode();</code>

那么nexthashcode()做了什么呢: 

正确理解ThreadLocal

<code>private</code> <code>static</code> <code>synchronized</code> <code>int</code> <code>nexthashcode() {  </code>

<code>    </code><code>int</code> <code>h = nexthashcode;  </code>

<code>    </code><code>nexthashcode = h + hash_increment;  </code>

<code>    </code><code>return</code> <code>h;  </code>

就是将threadlocal类的下一个hashcode值即nexthashcode的值赋给实例的threadlocalhashcode,然后nexthashcode的值增加hash_increment这个值。 

因此threadlocal实例的变量只有这个threadlocalhashcode,而且是final的,用来区分不同的threadlocal实例,threadlocal类主要是作为工具类来使用,那么threadlocal.set()进去的对象是放在哪儿的呢? 

看一下上面的set()方法,两句合并一下成为 

正确理解ThreadLocal

<code>threadlocalmap map = thread.currentthread().threadlocals;</code>

这个threadlocalmap 类是threadlocal中定义的内部类,但是它的实例却用在thread类中: 

正确理解ThreadLocal

<code>public</code> <code>class</code> <code>thread </code><code>implements</code> <code>runnable {  </code>

<code>    </code><code>......  </code>

<code>    </code><code>/* threadlocal values pertaining to this thread. this map is maintained </code>

<code>     </code><code>* by the threadlocal class. */</code>  

<code>    </code><code>threadlocal.threadlocalmap threadlocals = </code><code>null</code><code>;    </code>

再看这句: 

正确理解ThreadLocal

<code>if</code> <code>(map != </code><code>null</code><code>)  </code>

<code>    </code><code>map.set(</code><code>this</code><code>, value);</code>

也就是将该threadlocal实例作为key,要保持的对象作为值,设置到当前线程的threadlocalmap 中,get()方法同样大家看了代码也就明白了,threadlocalmap 类的代码太多了,我就不帖了,自己去看源码吧。 

写了这么多,也不知讲明白了没有,有什么不当的地方还请大家指出来。

特别说明:尊重作者的劳动成果,转载请注明出处哦~~~http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt107