Java 中的 ThreadLocal 简介

Java 中的 ThreadLocal 简介

介绍

了解 java.lang 包中的 ThreadLocal 构造。 能够为当前线程单独存储数据 - 并简单地将其包装在特殊类型的对象中。

ThreadLocal API

TheadLocal 构造允许存储只能由特定线程访问的数据。

假设想要一个与特定线程捆绑在一起的 Integer 值:

ThreadLocal threadLocalValue = new ThreadLocal<>();

接下来,想从线程使用这个值时,只需要调用 get() 或 set() 方法。 简单地说,可以认为 ThreadLocal 将数据存储在一个映射中——以线程为键。

因此,当在 threadLocalValue 上调用 get() 方法时,将获得请求线程的整数值:

threadLocalValue.set(1);

Integer result = threadLocalValue.get();

可以通过使用 withInitial() 静态方法来构造 ThreadLocal 的实例:

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

要从 ThreadLocal 中删除值,可以调用 remove() 方法:

threadLocal.remove();

要了解如何正确使用 ThreadLocal,首先,我查看一个不使用 ThreadLocal 的示例,然后重写示例以利用该构造。

使用Map存储用户数据

设计一个需要为每个给定的用户 ID 存储用户特定的上下文数据的程序:

public class Context {
    
    
    private String userName;

    public Context(String userName) {
    
    
        this.userName = userName;
    }

    @Override
    public String toString() {
    
    
        return "Context{" +
                "userName='" + userName + '\'' +
                '}';
    }
}

每个用户 ID 有一个线程。 将创建一个实现 Runnable 接口的 SharedMapWithUserContext 类。 run() 方法中模拟获取用户名,该类返回给定 userId 的 Context 对象。

接下来,将该上下文存储在由 userId 键控的 ConcurentHashMap 中:

public class SharedMapWithUserContext implements Runnable{
    
    

    public static Map<Integer, Context> userContextPerUserId
            = new ConcurrentHashMap<>();
    private Integer userId;
    private CountDownLatch countDownLatch;

    @Override
    public void run() {
    
    
        String userName = userId+System.currentTimeMillis()+"";
        userContextPerUserId.put(userId, new Context(userName));
        countDownLatch.countDown();
    }

    public SharedMapWithUserContext(Integer userId, CountDownLatch countDownLatch ) {
    
    
        this.userId = userId;
        this.countDownLatch = countDownLatch;
    }
}

可以通过两个不同的 userId 创建和启动两个线程,可以获取到 userContextPerUserId 映射中有两个条目:

public class SharedMapWithUserContextMain {
    
    

    public static void main(String[] args) throws InterruptedException {
    
    
        //CountDownLatch目的让两个线程执行完 获取执行结果 
        CountDownLatch countDownLatch = new CountDownLatch(2);
        SharedMapWithUserContext firstUser = new SharedMapWithUserContext(1,countDownLatch);
        SharedMapWithUserContext secondUser = new SharedMapWithUserContext(2,countDownLatch);
        new Thread(firstUser).start();
        new Thread(secondUser).start();
        countDownLatch.await();
        System.out.println(SharedMapWithUserContext.userContextPerUserId.size());//2
    }
}

使用ThreadLocal存储用户数据

重写示例以使用 ThreadLocal 存储用户 Context 实例。 每个线程都有自己的 ThreadLocal 实例。

使用 ThreadLocal 时,需要非常小心,因为每个 ThreadLocal 实例都与一个特定的线程相关联。 在示例中,为每个特定的 userId 设置了一个专用线程。

run() 方法将获取用户上下文并使用 set() 方法将其存储到 ThreadLocal 变量中:

public class ThreadLocalWithUserContext implements Runnable {
    
    

    private static ThreadLocal<Context> userContext
            = new ThreadLocal<>();
    private Integer userId;


    @Override
    public void run() {
    
    
        String userName = userId+System.currentTimeMillis()+"";
        userContext.set(new Context(userName));
        System.out.println("线程上下文用户id: "
                + userId + " 信息为: " + userContext.get());
    }

    public ThreadLocalWithUserContext(Integer userId) {
    
    
        this.userId = userId;
    }
}

通过启动两个线程来测试:

public class ThreadLocalWithUserContextMain {
    
    

    public static void main(String[] args) {
    
    
        ThreadLocalWithUserContext firstUser
                = new ThreadLocalWithUserContext(1);
        ThreadLocalWithUserContext secondUser
                = new ThreadLocalWithUserContext(2);
        new Thread(firstUser).start();
        new Thread(secondUser).start();
    }
}

运行此代码后,将在标准输出中看到为每个给定线程设置了 ThreadLocal:

线程上下文用户id: 2 信息为: Context{userName=‘1625705034928’}
线程上下文用户id: 1 信息为: Context{userName=‘1625705034927’}

ThreadLocal 和线程池

ThreadLocal 提供了一个易于使用的 API 来限制每个线程的一些值。 这是在 Java 中实现线程安全的合理方式。 但是,当一起使用 ThreadLocals 和线程池时,应该格外小心。

考虑以下场景:

  • 首先,应用程序从线程池中获取一个线程。
  • 然后将一些线程限制值存储到当前线程的 ThreadLocal 中。
  • 当前执行完成后,应用程序将获取的线程还回线程池
  • 过了一会儿,应用程序获取同一个线程来处理另一个请求。
  • 由于应用程序上次没有执行必要的清理,它可能会为新请求重新使用相同的 ThreadLocal 数据。

解决此问题的一种方法是在使用完每个 ThreadLocal 后手动删除它。 因为这种方法需要严格的代码审查,很容易出错。

扩展 ThreadPoolExecutor

事实证明,可以扩展 ThreadPoolExecutor 类并为 beforeExecute() 和 afterExecute() 方法提供自定义钩子实现。 在使用借用的线程运行任何东西之前,线程池将调用 beforeExecute() 方法。 另一方面,它会在执行我们的逻辑后调用 afterExecute() 方法。

因此,可以扩展 ThreadPoolExecutor 类,并在 afterExecute() 方法中移除 ThreadLocal 数据

public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
    
    

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
    
    
        //移除每一个ThreadLocal数据
    }
}

如果我将请求提交给 ExecutorService 这个实现,那么可以确保使用 ThreadLocal 和线程池不会给的用程序带来安全隐患。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/niugang0920/article/details/119046105