一、ThreadLocal概述
在Java开发中,多线程是一个永远绕不开的话题。Java服务器中通常使用一组线程处理一个会话或一个连接,这一组线程一般具有父子关系,它们往往需要客户端传递的用户信息来完成业务逻辑,这些信息仅针对本次连接或会话有效。当然我们可以以参数的形式传递这些数据,但当参数异常复杂的时候,层间传递就变得很枯燥,有没有一种方法可以简化这种场景?当然有,他就是ThreadLocal技术,ThreadLocal是一种线程局部变量共享机制,它独立于语言,但本次仅讨论Java语言范畴。
使用ThreadLocal
维护的变量在每个线程内部维护一个副本,对该变量的修改仅对该线程可见(指ThreadLocal.set(obj),对象成员修改除外),同样可以在线程内部的任意位置使用它。这样,既满足了线程之间的隔离要求,又减少了参数的传递工作,何乐而不为之!另外,我们上面提到,如果是一组线程(这一组线程具有父子关系)需要变量共享呢?没问题,Java给我们提供了InheritableThreadLocal
,只要我们在父线程中设置了相关变量,子线程会自动继承这些变量的值,但本质上是子线程初始化自己的副本时使用了父线程的值,此后对各自副本的修改(指ThreadLocal.set(obj),对象成员修改除外)也仅在当前线程生效。
注意,网上很多博客写着ThreadLocal是用来解决多线程并发问题的,这种理解在我看来是错误的。多线程并发指的是多个线程对同一个临界区操作的互斥问题,或多个线程之间的同步问题,而ThreadLocal在每个线程都有一个副本,不存在互斥,也不存在同步,因此跟多线程并发问题无关。
二、ThreadLocal运用
上面简单介绍了ThreadLocal的性质,下面来看一下具体的运用场景:
Session管理:正如我们开篇提到的用户信息传递问题,本质上就是一个Session管理,它在一次会话开始的时候创建ThreadLocal变量保存所有全局信息,会话结束的时候释放ThreadLocal。如果线程的生命周期与会话的生命周期一致,则可以不用手动释放ThreadLocal变量,如果使用了线程池就必须在提交任务时手动初始化ThreadLocal,结束任务时手动清理ThreadLocal保存的数据,否则就可能使用的前一个会话遗留的脏数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @RestController public class UserController { private static final ThreadLocal<UserInfo> USER_INFO = new ThreadLocal<>(); private static final Executor EXECUTOR = Executors.newFixedThreadPool(10); @Autowired private UserService userService; @RequestMapping("/user") public User login(UserInfo userInfo) { USER_INFO.set(userInfo); User user = userService.login(); EXECUTOR.execute(()->{ USER_INFO.set(userInfo); userService.doSomething(); USER_INFO.remove(); }); return user; } }
|
连接管理:当我们有一个线程池用来处理一些远程任务,每个任务都需要与远程主机建立连接,那么为了减少频繁建立连接带来的性能开销,我们可以使用ThreadLocal来保存这些连接,使之与线程的生命周期一致,这样就避免了频繁建立远程连接带来的开销。
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
| @RestController public class UserController { private static final ThreadLocal<UserInfo> USER_INFO = new ThreadLocal<>(); private static final ThreadLocal<RemoteConnection> REMOTE_CONNECTION = new ThreadLocal<>(); private static final Executor EXECUTOR = Executors.newFixedThreadPool(10);
@Autowired private UserService userService;
@RequestMapping("/user") public User login(UserInfo userInfo) { USER_INFO.set(userInfo); User user = userService.login(); EXECUTOR.execute(()->{ USER_INFO.set(userInfo); RemoteConnection connection = REMOTE_CONNECTION.get(); if(connection == null) { connection = RemoteUtil.getConnection(); REMOTE_CONNECTION.set(connection); } userService.doSomething(connection); USER_INFO.remove(); }); return user; } }
|
ThreadLocal在Spring事务管理中的应用
三、ThreadLocal原理
3.1 ThreadLocal原理
事实上ThreadLocal本身并不存储数据,它只是数据的 管家 。在Thread内部有threadLocals
(对应ThreadLocal
)和inheritableThreadLocals
(对应InheritableThreadLocal
)两个Map(它们也是hash map,但有自己的实现),它们维护者ThreadLocal/InheritableThreadLocal的副本。下面以threadLocals为例,threadLocals类型是ThreadLocal.ThreadLocalMap
,它定义在ThreadLocal类中,其key是ThreadLocal变量的弱引用,value是对应副本值。
对于同一个ThreadLocal在不同Thread中,threadLocals中的key是同一个对象,这确保了同一个threadLocal变量能检索到 同一个类型 的value,但value在不同线程之间是独立的。
对于不同ThreadLocal在同一个线程中来说,不同的Thread Local对应 不同类型 的值,也就是threadLocals中的多个entry。
ThreadLocalMap中的key继承了WeakReference
,因为ThreadLocal对于用户而言就是一个普通变量,它的生命周期应当符合一般变量行为。如果这里是强引用,那么即便用户将其引用置为null(或者方法返回、对象回收等等),该ThreadLocal对象可能依然无法被回收,因为还有其他线程的threadLocalMap中的entry对其有强引用。
将Entry中的key设为弱引用即可解决ThreadLocal GC回收的问题,但对应value又会带来内存泄露,对于value而言依然有thread -> threadLocalMap -> entry -> value
这样的引用链存在,且该value永远无法被访问,直到线程结束。为解决这一问题,该Map中新增了部分对”stale entry”的回收逻辑。
3.2 ThreadLocal源码
点击展开代码
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 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
| public class ThreadLocal<T> { private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode = new AtomicInteger(); private static final int HASH_INCREMENT = 0x61c88647; private static int nextHashCode() { return nextHashCode.getAndAdd(HASH_INCREMENT); } protected T initialValue() { return null; } public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) { return new SuppliedThreadLocal<>(supplier); } public ThreadLocal() { } 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(); } 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; } public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) { return new ThreadLocalMap(parentMap); } T childValue(T parentValue) { throw new UnsupportedOperationException(); } static final class SuppliedThreadLocal<T> extends ThreadLocal<T> { private final Supplier<? extends T> supplier; SuppliedThreadLocal(Supplier<? extends T> supplier) { this.supplier = Objects.requireNonNull(supplier); } @Override protected T initialValue() { return supplier.get(); } } static class ThreadLocalMap { static class Entry extends WeakReference<ThreadLocal<?>> { Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } private static final int INITIAL_CAPACITY = 16; private Entry[] table; private int size = 0; private int threshold; private void setThreshold(int len) { threshold = len * 2 / 3; } private static int nextIndex(int i, int len) { return ((i + 1 < len) ? i + 1 : 0); } private static int prevIndex(int i, int len) { return ((i - 1 >= 0) ? i - 1 : len - 1); } ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) { table = new Entry[INITIAL_CAPACITY]; int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); table[i] = new Entry(firstKey, firstValue); size = 1; setThreshold(INITIAL_CAPACITY); } private ThreadLocalMap(ThreadLocalMap parentMap) { Entry[] parentTable = parentMap.table; int len = parentTable.length; setThreshold(len); table = new Entry[len]; for (int j = 0; j < len; j++) { Entry e = parentTable[j]; if (e != null) { @SuppressWarnings("unchecked") ThreadLocal<Object> key = (ThreadLocal<Object>) e.get(); if (key != null) { Object value = key.childValue(e.value); Entry c = new Entry(key, value); int h = key.threadLocalHashCode & (len - 1); while (table[h] != null) h = nextIndex(h, len); table[h] = c; size++; } } } } private Entry getEntry(ThreadLocal<?> key) { int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); } private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) { Entry[] tab = table; int len = tab.length; while (e != null) { ThreadLocal<?> k = e.get(); if (k == key) return e; if (k == null) expungeStaleEntry(i); else i = nextIndex(i, len); e = tab[i]; } return null; } private void set(ThreadLocal<?> key, Object value) { 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(); } private void remove(ThreadLocal<?> key) { 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)]) { if (e.get() == key) { e.clear(); expungeStaleEntry(i); return; } } } private void replaceStaleEntry(ThreadLocal<?> key, Object value, int staleSlot) { Entry[] tab = table; int len = tab.length; Entry e; int slotToExpunge = staleSlot; for (int i = prevIndex(staleSlot, len); (e = tab[i]) != null; i = prevIndex(i, len)) { if (e.get() == null) slotToExpunge = i; } for (int i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) { ThreadLocal<?> k = e.get(); if (k == key) { e.value = value; tab[i] = tab[staleSlot]; tab[staleSlot] = e; if (slotToExpunge == staleSlot) slotToExpunge = i; cleanSomeSlots(expungeStaleEntry(slotToExpunge), len); return; } if (k == null && slotToExpunge == staleSlot) slotToExpunge = i; } tab[staleSlot].value = null; tab[staleSlot] = new Entry(key, value); if (slotToExpunge != staleSlot) cleanSomeSlots(expungeStaleEntry(slotToExpunge), len); } private int expungeStaleEntry(int staleSlot) { Entry[] tab = table; int len = tab.length; tab[staleSlot].value = null; tab[staleSlot] = null; size--; Entry e; int i; for (i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) { ThreadLocal<?> k = e.get(); if (k == null) { e.value = null; tab[i] = null; size--; } else { int h = k.threadLocalHashCode & (len - 1); if (h != i) { tab[i] = null; while (tab[h] != null) h = nextIndex(h, len); tab[h] = e; } } } return i; } private boolean cleanSomeSlots(int i, int n) { boolean removed = false; Entry[] tab = table; int len = tab.length; do { i = nextIndex(i, len); Entry e = tab[i]; if (e != null && e.get() == null) { n = len; removed = true; i = expungeStaleEntry(i); } } while ( (n >>>= 1) != 0); return removed; }
private void rehash() { expungeStaleEntries(); if (size >= threshold - threshold / 4) resize(); }
private void resize() { Entry[] oldTab = table; int oldLen = oldTab.length; int newLen = oldLen * 2; Entry[] newTab = new Entry[newLen]; int count = 0; for (int j = 0; j < oldLen; ++j) { Entry e = oldTab[j]; if (e != null) { ThreadLocal<?> k = e.get(); if (k == null) { e.value = null; } else { int h = k.threadLocalHashCode & (newLen - 1); while (newTab[h] != null) h = nextIndex(h, newLen); newTab[h] = e; count++; } } } setThreshold(newLen); size = count; table = newTab; } private void expungeStaleEntries() { Entry[] tab = table; int len = tab.length; for (int j = 0; j < len; j++) { Entry e = tab[j]; if (e != null && e.get() == null) expungeStaleEntry(j); } } }
|