Interview Shredded ThreadLocal! ! !

Explanation

Interviewer: Tell me about some of your understanding of the ThreadLocal.

So how can we answer it? ? ? ? Under You can also think, ponder below zero and see;

  • ThreadLocal used in any place?

  • ThreadLocal some of the details!

  • Best Practices of ThreadLocal!

  • Think

ThreadLocal used in any place?

Under discussion ThreadLocal used before somewhere, let's clear, if only on a thread, then do not talk about the ThreadLocal, ThreadLocal is multithreaded scene! ! !

Use ThreadLocal induction down to the class 2:

  • Save the thread context information can be obtained at any desired place! ! !

  • Thread-safe, avoid certain situations need to consider the performance loss caused by thread safety must be synchronized! ! !

Save the thread context information can be obtained at any desired place! ! !

Due to the nature of ThreadLocal, the same thread is set in a place, at any subsequent places you can get to. It can be used to save the thread context information.

How common such as a string of subsequent associate each request, may be performed with ThreadLocal set, need to log recording method in which subsequent to the acquisition request get arbitrarily id, string together such that the entire request.

For example, there are Spring's transaction management, with ThreadLocal storage Connection, so that each can get the same DAO Connection, transaction rollback can be submitted and other operations.

Note:  ThreadLocal this useful, are often used in some excellent inside the framework, we generally had little contact, but the following scenario we touch some more!

Thread-safe, avoid certain situations need to consider the performance loss caused by thread safety must be synchronized! ! !

ThreadLocal provides a new way to solve the problem of concurrent multi-threaded programs. ThreadLocal but there are limitations, let's look at Ali specification:


1


Each thread to read and write data in ThreadLocal thread is isolated from each other will not affect, so ThreadLocal can not solve the problem shared object updates!

Since no sharing of information, there is no natural competition problem, thus ensuring the performance loss in some cases the security thread, and avoid some of the cases to consider thread safety must be synchronized brings! ! !

Such scenes Ali specification which also mentioned:


1


ThreadLocal some of the details!

ThreaLocal使用示例代码:

public class ThreadLocalTest {     
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();     
public static void main(String[] args) {         
new Thread(() -> {             
try {                 
for (int i = 0; i < 100; i++) {                     
threadLocal.set(i);                     
System.out.println(Thread.currentThread().getName() + "====" + threadLocal.get());                     
try {                         
Thread.sleep(200);                     
} catch (InterruptedException e) {                         
e.printStackTrace();                     
}                 
}             
} finally {                 
threadLocal.remove();             
}         
}, 
"threadLocal1").start();         
new Thread(() -> {             
try {                 
for (int i = 0; i < 100; i++) {                     
System.out.println(Thread.currentThread().getName() + "====" + threadLocal.get());                     
try {                         
Thread.sleep(200);                     
} catch (InterruptedException e) {                         
e.printStackTrace();                     
}                 
}             
} finally {                 
threadLocal.remove();             
}         
}, 
"threadLocal2").start();     
} 
}

代码截图:

1


代码运行结果:


1


从运行的结果我们可以看到threadLocal1进行set值对threadLocal2并没有任何影响!

Thread、ThreadLocalMap、ThreadLocal总览图


1



1


Thread类有属性变量threadLocals (类型是ThreadLocal.ThreadLocalMap),也就是说每个线程有一个自己的ThreadLocalMap ,所以每个线程往这个ThreadLocal中读写隔离的,并且是互相不会影响的。

一个ThreadLocal只能存储一个Object对象,如果需要存储多个Object对象那么就需要多个ThreadLocal!!!

如图:


1


看到上面的几个图,大概思路应该都清晰了,我们Entry的key指向ThreadLocal用虚线表示弱引用 ,下面我们来看看ThreadLocalMap:


1


java对象的引用包括 : 强引用,软引用,弱引用,虚引用 。

因为这里涉及到弱引用,简单说明下:

弱引用也是用来描述非必需对象的,当JVM进行垃圾回收时,无论内存是否充足,该对象仅仅被弱引用关联,那么就会被回收。

当仅仅只有ThreadLocalMap中的Entry的key指向ThreadLocal的时候,ThreadLocal会进行回收的!!!

ThreadLocal被垃圾回收后,在ThreadLocalMap里对应的Entry的键值会变成null,但是Entry是强引用,那么Entry里面存储的Object,并没有办法进行回收,所以ThreadLocalMap 做了一些额外的回收工作。


1


虽然做了但是也会存在内存泄漏风险(我没有遇到过,网上很多类似场景,所以会提到后面的ThreadLocal最佳实践!!!

ThreadLocal的最佳实践!

ThreadLocal被垃圾回收后,在ThreadLocalMap里对应的Entry的键值会变成null,但是Entry是强引用,那么Entry里面存储的Object,并没有办法进行回收,所以ThreadLocalMap 做了一些额外的回收工作。


1


Note:  In many cases, we are using the thread pool scene, does not stop, will not destroy the basic thread! ! !

Because of the life cycle is very long thread, if we set a very big target Object to ThreadLocal inside, although set, get and so on method calls in certain conditions additional clean-up, but ThreadLocal after being garbage collected, in ThreadLocalMap Entry of the key in the corresponding will become null, but not in a subsequent operation set, get the other methods.

So best practice, we should not use the initiative to call the remove method to clean up.


1


Here the ThreadLocal defined as static Another advantage is that, due to the strong references in ThreadLocal, then ThreadLocalMap in the corresponding Entry key will always exist, then remove the execution time can be properly positioned and delete! ! !

Best practices should be:

try {// Other business logic} finally {threadLocal objects .remove ();} copy the code


1


Think

If the interview, you can put the above content can be talked about, personally feel very good, answered on the very perfect. But if you can answer the following, then even more perfect.

For ThreadLocal, I was watching Netty source, but also to find out about FastThreadLocal, xxxxx a series content, it is a upgrade.


1


I tested locally, FastThreadLocal throughput is about three times the jdkThreadLocal.



Guess you like

Origin blog.51cto.com/14378044/2416748