运行在tomcat容器中的ThreadLocal容易产生的问题

ThreadLocal在tomcat容器中的的生命周期并不等于web request的生命周期,所以(以下讨论的是tomcat容器中使用ThreadLocal),所以ThreadLocal不应保存与请求会影响的相关的信息。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("threadLocalRunInTomcatTest")
public class ThreadLocalRunInTomcatTestController {

    private static final ThreadLocal<String> currentUserId = ThreadLocal.withInitial(() -> null);

    @GetMapping("fail")
    public String fail(@RequestParam("uid") String uid) {
        String before  = Thread.currentThread().getName() + ":" + currentUserId.get();
        currentUserId.set(uid);
        String after  = Thread.currentThread().getName() + ":" + currentUserId.get();
        return before+"\n"+after;
    }

    @GetMapping("success")
    public String success(@RequestParam("userId") String userId) {
        String before  = Thread.currentThread().getName() + ":" + currentUserId.get();
        currentUserId.set(userId);
        try {
            String after = Thread.currentThread().getName() + ":" + currentUserId.get();
            return before+"\n"+after;
        } finally {
            currentUserId.remove();
        }
    }
}

先测试一下fail的请求:
currentUserId是用来存储当前用户的唯一键的,
第一次请求 127.0.0.1:1003/threadLocalRunInTomcatTest/fail?uid=2
返回结果为:
http-nio-1003-exec-1:null
http-nio-1003-exec-1:2
这时候结果是对的;

第二次请求 127.0.0.1:45678/threadLocalRunInTomcatTest/fail?uid=3
(将uid的value改为3)
结果为:
http-nio-45678-exec-1:2
http-nio-45678-exec-1:3

分析:
我们返回的数据格式为: return before+"\n"+after;
所以第一次,before为null,after为2
第二次,before为2 ,after为3。
显而易见的是,web 请求的周期不同于threadLocal的周期;这是因为线程的创建太过昂贵,被重复利用了。知道原因后,可以在最后添加一个localthread的remove进行数据删除。

测试success的请求:
127.0.0.1:45678/threadLocalRunInTomcatTest/success?userId=2

不管请求多少次,每次都返回:
http-nio-45678-exec-1:null
http-nio-45678-exec-1:2

发布了2 篇原创文章 · 获赞 1 · 访问量 13

猜你喜欢

转载自blog.csdn.net/qq_24510649/article/details/105013382
今日推荐