java中ThreadLocal的使用

文章目录

java中ThreadLocal的使用

ThreadLocal主要用来为当前线程存储数据,这个数据只有当前线程可以访问。

在定义ThreadLocal的时候,我们可以同时定义存储在ThreadLocal中的特定类型的对象。

ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();

上面我们定义了一个存储Integer的ThreadLocal对象。

要存储和获取ThreadLocal中的对象也非常简单,使用get()和set()即可:

1threadLocalValue.set(1); 2Integer result = threadLocalValue.get();

我可以将ThreadLocal看成是一个map,而当前的线程就是map中的key。

除了new一个ThreadLocal对象,我们还可以通过:

1public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) { 2 return new SuppliedThreadLocal<>(supplier); 3 }

ThreadLocal提供的静态方法withInitial来初始化一个ThreadLocal。

ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);

withInitial需要一个Supplier对象,通过调用Supplier的get()方法获取到初始值。

要想删除ThreadLocal中的存储数据,可以调用:

threadLocal.remove();

下面我通过两个例子的对比,来看一下使用ThreadLocal的好处。

在实际的应用中,我们通常会需要为不同的用户请求存储不同的用户信息,一般来说我们需要构建一个全局的Map,来根据不同的用户ID,来存储不同的用户信息,方便在后面获取。

在Map中存储用户数据

我们先看下如果使用全局的Map该怎么用:

1public class SharedMapWithUserContext implements Runnable { 2 3 public static Map<Integer, Context> userContextPerUserId 4 = new ConcurrentHashMap<>(); 5 private Integer userId; 6 private UserRepository userRepository = new UserRepository(); 7 8 public SharedMapWithUserContext(int i) { 9 this.userId=i; 10 } 11 12 @Override 13 public void run() { 14 String userName = userRepository.getUserNameForUserId(userId); 15 userContextPerUserId.put(userId, new Context(userName)); 16 } 17}

这里我们定义了一个static的Map来存取用户信息。

再看一下怎么使用:

1@Test 2 public void testWithMap(){ 3 SharedMapWithUserContext firstUser = new SharedMapWithUserContext(1); 4 SharedMapWithUserContext secondUser = new SharedMapWithUserContext(2); 5 new Thread(firstUser).start(); 6 new Thread(secondUser).start(); 7 assertEquals(SharedMapWithUserContext.userContextPerUserId.size(), 2); 8 }

在ThreadLocal中存储用户数据

如果我们要在ThreadLocal中使用可以这样:

1public class ThreadLocalWithUserContext implements Runnable { 2 3 private static ThreadLocal<Context> userContext 4 = new ThreadLocal<>(); 5 private Integer userId; 6 private UserRepository userRepository = new UserRepository(); 7 8 public ThreadLocalWithUserContext(int i) { 9 this.userId=i; 10 } 11 12 @Override 13 public void run() { 14 String userName = userRepository.getUserNameForUserId(userId); 15 userContext.set(new Context(userName)); 16 System.out.println("thread context for given userId: " 17 + userId + " is: " + userContext.get()); 18 } 19 20}

测试代码如下:

1public class ThreadLocalWithUserContextTest { 2 3 @Test 4 public void testWithThreadLocal(){ 5 ThreadLocalWithUserContext firstUser 6 = new ThreadLocalWithUserContext(1); 7 ThreadLocalWithUserContext secondUser 8 = new ThreadLocalWithUserContext(2); 9 new Thread(firstUser).start(); 10 new Thread(secondUser).start(); 11 } 12}

运行之后,我们可以得到下面的结果:

1thread context for given userId: 1 is: com.flydean.Context@411734d4 2thread context for given userId: 2 is: com.flydean.Context@1e9b6cc

不同的用户信息被存储在不同的线程环境中。

注意,我们使用ThreadLocal的时候,一定是我们可以自由的控制所创建的线程。如果在ExecutorService环境下,就最好不要使用ThreadLocal,因为在ExecutorService中,线程是不可控的。

本文的例子可以参考https://github.com/ddean2009/learn-java-concurrency/tree/master/ThreadLocal

更多教程请参考 flydean的博客

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Opencv中Mat矩阵相乘——点乘、dot、mul运算详解

Opencv中Mat矩阵相乘——点乘、dot、mul运算详解2016年09月02日00:00:36 \牧野(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fme.csdn.net%2Fdcrmg) 阅读数:59593