标签:before get strong finally after ram private inf http
ThreadLocal 适用于变量在线程间隔离,而在方法或类间共享的场景。
1 @RestController 2 public class ThreadLocalController { 3 private static final ThreadLocal<String> currentUid = ThreadLocal.withInitial(() -> null); 4 @GetMapping("bad") 5 public Map doBad(@RequestParam("uid") String uid) { 6 String before = currentUid.get(); 7 currentUid.set(uid); 8 String after = currentUid.get(); 9 Map result = new HashMap(); 10 result.put("before", before); 11 result.put("after", after); 12 return result; 13 } 14 }
在application中做一下tomcat的配置
server.tomcat.max-threads=1
按理说before总是null才对,为什么第二次运行却读取到了第一次的值呢?
只是因为我们的tocat会开启一个线程来调用我们的程序,而tomcat本身是有线程池的,会出现线程复用的情况。所以导致了问题。
1 @RestController 2 public class ThreadLocalController { 3 private static final ThreadLocal<String> currentUid = ThreadLocal.withInitial(() -> null); 4 @GetMapping("good") 5 public Map doGood(@RequestParam("uid") String uid) { 6 7 try { 8 String before = currentUid.get(); 9 currentUid.set(uid); 10 String after = currentUid.get(); 11 Map result = new HashMap(); 12 result.put("before", before); 13 result.put("after", after); 14 return result; 15 } finally { 16 currentUid.remove(); 17 } 18 } 19 }
tomcat线程池。
标签:before get strong finally after ram private inf http
原文地址:https://www.cnblogs.com/Brake/p/12694666.html