当前位置:网站首页>Work accumulation - problems encountered in using ThreadLocal in web requests
Work accumulation - problems encountered in using ThreadLocal in web requests
2022-06-26 06:06:00 【Big wind】
Find the error
When we implement the business, we will use some data only for the current thread
ThreadLocalSave up , Take it out at a certain time of business execution , Because of the thread isolation feature, we don't have to worry about other threads accessing wrong data .
Recently I met a BUG, The same business obtains different return results in the request . Later it was found that `ThreadLocal`` The problems caused .
ThreadLocal Data is shared ?
ThreadLocal The data of is thread isolation, which has been introduced by many people , As the thread destroys , Data will also be destroyed . One reason why different requests can access data in other requests may be ThreadLocal The data in has not been destroyed after use , Threads are reused . This scenario can be simulated using a thread pool .
In the following code, we simulate to ThreadLocal Setting parameters in , The thread pool reuses a fixed number of threads , Once threads are reused ThreadLocal If the data in is not cleared, a new task will read the old data
private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(2,2,0, TimeUnit.SECONDS,new LinkedBlockingDeque<>(12));
List<Runnable> runList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
runList.add(() -> {
System.out.println(" Current thread :" + Thread.currentThread().getName());
String value = threadLocal.get();
if (value == null) {
threadLocal.set(Thread.currentThread().getName());
System.out.println("threadLocal There is no data , Set parameters :" + Thread.currentThread().getName());
} else {
System.out.println("threadLocal Existing data , Parameters :" + value);
}
});
}
runList.forEach(executorService::execute);
executorService.shutdown();
}
In the output results, you can see that errors have occurred in the following tasks , Read the data of the previous thread
Current thread :pool-1-thread-1
Current thread :pool-1-thread-2
threadLocal There is no data , Set parameters :pool-1-thread-1
threadLocal There is no data , Set parameters :pool-1-thread-2
Current thread :pool-1-thread-1
threadLocal Existing data , Parameters :pool-1-thread-1
Current thread :pool-1-thread-2
threadLocal Existing data , Parameters :pool-1-thread-2
Current thread :pool-1-thread-1
threadLocal Existing data , Parameters :pool-1-thread-1
Tomcat Worker thread
As can be found in the above example , When there is thread reuse ThreadLocal If the data of this thread is not cleaned up in time, it will cause the business of this thread to read wrong data . and
Tomcat The worker thread executing the request is obtained from the thread pool , In the official documentation about thread pool configuration https://tomcat.apache.org/tomcat-8.5-doc/config/executor.html#Standard_Implementation The default thread pool is specified in the article org.apache.catalina.core.StandardThreadExecutor.
By analyzing the initialization method and the logic inside, we can find ,StandardThreadExecutor The implementation of is essentially through ThreadPoolExecutor Achieve business .
@Override
protected void startInternal() throws LifecycleException {
taskqueue = new TaskQueue(maxQueueSize);
TaskThreadFactory tf = new TaskThreadFactory(namePrefix,daemon,getThreadPriority());
executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);
executor.setThreadRenewalDelay(threadRenewalDelay);
if (prestartminSpareThreads) {
executor.prestartAllCoreThreads();
}
taskqueue.setParent(executor);
setState(LifecycleState.STARTING);
}
It should be noted that :Tomcat The name of the thread pool is also called ThreadPoolExecutor, Is inherited JDK Of ThreadPoolExecutor Then some logic encapsulation is carried out .
Tomcat The thread queue of is saved in org.apache.tomcat.util.threads.TaskQueue Is the above code taskqueue = new TaskQueue(maxQueueSize).
You can see Tomcat In order to provide the efficiency of processing requests, the thread pool is also used to process requests , This means that threads will be reused , So when using some thread variables , If you don't actively request these data after the task ends , This data will pollute the thread and cause subsequent business errors .
ThreadLocal The problem is not ThreadLocal The problem of
ThreadLocal As a tool that can set threads to share data , Can achieve a lot of business . Many times, when we implement some logic, we don't realize that these logic have been running in a multithreaded environment . The use of good ThreadLocal, Not only to understand ThreadLocal Also understand the operation ThreadLocal Environment . Sometimes ThreadLocal The problem is not ThreadLocal The problems that arise
边栏推荐
- 状态模式,身随心变
- 04. basic data type - list, tuple
- numpy.random.choice
- Day2- syntax basis and variables
- Mongodb——使用Mongodb对字段中字符串内容进行截取,并进行分组统计
- Explore small program audio and video calls and interactive live broadcast from New Oriental live broadcast
- Implementation of third-party wechat authorized login for applet
- String类学习
- E-commerce seeks growth breakthrough with the help of small program technology
- Selective search for object recognition paper notes [image object segmentation]
猜你喜欢
随机推荐
Definition of Halcon hand eye calibration
How to associate wechat applet QR code to realize two code aggregation
Getting to know concurrency problems
Getting started with Python
421- binary tree (226. reversed binary tree, 101. symmetric binary tree, 104. maximum depth of binary tree, 222. number of nodes of complete binary tree)
How to use the tablet as the second extended screen of the PC
numpy.random.choice
The difference between overload method and override method
SQL Server 函数
kolla-ansible部署openstack yoga版本
Sql语法中循环的使用
【C语言】深度剖析数据在内存中的存储
On site commissioning - final method of kb4474419 for win7 x64 installation and vs2017 flash back
Implement the runnable interface
numpy.tile()
Yamaha robot splits visual strings
Library management system
Overloading and overriding
电商借助小程序技术发力寻找增长突破口
Day4 branch and loop









