运行在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:1003/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:1003/threadLocalRunInTomcatTest/success?userId=2

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值