Java并发编程之线程局部变量ThreadLocal
发布日期:2021-06-29 02:39:44 浏览次数:2 分类:技术文章

本文共 4318 字,大约阅读时间需要 14 分钟。

什么是ThreadLocal变量

ThreadLoal 变量,线程局部变量,同一个ThreadLocal所包含的对象,在不同的Thread中有不同的副本。这里有几点需要注意:

  • 因为每个 Thread 内有自己的实例副本,且该副本只能由当前 Thread 使用。这是也是 ThreadLocal 命名的由来。
  • 既然每个 Thread 有自己的实例副本,且其它 Thread 不可访问,那就不存在多线程间共享的问题。

ThreadLocal 提供了线程本地的实例。它与普通变量的区别在于,每个使用该变量的线程都会初始化一个完全独立的实例副本。ThreadLocal 变量通常被private static修饰。当一个线程结束时,它所使用的所有 ThreadLocal 相对的实例副本都可被回收。

总的来说,ThreadLocal 适用于每个线程需要自己独立的实例且该实例需要在多个方法中被使用,也即变量在线程间隔离而在方法或类间共享的场景。 后文会通过实例详细阐述该观点。另外,该场景下,并非必须使用 ThreadLocal ,其它方式完全可以实现同样的效果,只是 ThreadLocal 使得实现更简洁。

不恰当的理解

错误理解1:ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。

错误理解2:ThreadLocal的目的是为了解决多线程访问资源时的共享问题。

合理的理解

ThreadLoal 变量,它的基本原理是,同一个 ThreadLocal 所包含的对象(对ThreadLocal< String >而言即为 String 类型变量),在不同的 Thread 中有不同的副本(实际是不同的实例,后文会详细阐述)。这里有几点需要注意:

  • 因为每个 Thread 内有自己的实例副本,且该副本只能由当前 Thread 使用。这是也是 ThreadLocal 命名的由来
  • 既然每个 Thread 有自己的实例副本,且其它 Thread 不可访问,那就不存在多线程间共享的问题
  • 既无共享,何来同步问题,又何来解决同步问题一说?

ThreadLocal的使用场景:

ThreadLocal 适用于如下两种场景:

  • To keep state with a thread (user-id, transaction-id, logging-id) 每个线程需要有自己单独的实例
  • To cache objects which you need frequently 实例需要在多个方法中共享,但不希望被多线程共享

对于第一点,每个线程拥有自己实例,实现它的方式很多。例如可以在线程内部构建一个单独的实例。ThreadLoca 可以以非常方便的形式满足该需求。

对于第二点,可以在满足第一点(每个线程有自己的实例)的条件下,通过方法间引用传递的形式实现。ThreadLocal 使得代码耦合度更低,且实现更优雅。

ThreadLocal的原理:

在每个线程中存储一个变量的副本,这样在每个线程对该变量进行使用的时候,使用的是该线程的变量副本,从而保证了线程的安全性以及高效性。

因为一个线程内可以存在多个 ThreadLocal 对象,所以其实是使用了ThreadLocal的静态内部类 ThreadLocalMap ,ThreadLocalMap维护了一个Entry数组Entry[], 每个Entry都维护着一个ThreadLocal对象。而我们使用的ThreadLocal的get()、set() 方法其实都是调用了这个ThreadLocalMap类对应的 get()、set() 方法。

//ThreadLocal.java    /**     * Sets the current thread's copy of this thread-local variable     * to the specified value.  Most subclasses will have no need to     * override this method, relying solely on the {@link #initialValue}     * method to set the values of thread-locals.     *     * @param value the value to be stored in the current thread's copy of     *        this thread-local.     */    public void set(T value) {
Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) {
map.set(this, value); } else {
createMap(t, value); } } /** * Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local */ public T get() {
Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) {
@SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }

最终的变量是放在了当前线程的 ThreadLocalMap 中,并不是存在 ThreadLocal 上,ThreadLocal 可以理解为只是ThreadLocalMap的封装,传递了变量值。

类的关系图:

public class Thread {
ThreadLocal.ThreadLocalMap threadLocals = null;}static class ThreadLocalMap {
private Entry[] table;}static class Entry {
ThreadLocal
k; /** The value associated with this ThreadLocal. */ Object value;}

使用注意

1.使用ThreadLocal,一般都是声明在静态变量中,如果不断创建ThreadLocal而没有调用其remove方法,将会导致内存泄露。

2.同时请注意,如果是static的ThreadLocal,一般不需要调用remove。

1)存储用户Session

一个简单的用ThreadLocal来存储Session的例子:

private static final ThreadLocal threadSession = new ThreadLocal(); public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get(); try {
if (s == null) {
s = getSessionFactory().openSession(); threadSession.set(s); } } catch (HibernateException ex) {
throw new InfrastructureException(ex); } return s;}

2)解决线程安全的问题

比如Java7中的SimpleDateFormat不是线程安全的,可以用ThreadLocal来解决这个问题:

public class DateUtil {
private static ThreadLocal
ThreadLocalFormat = new ThreadLocal
() {
@Override protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static String formatDate(Date date) {
return ThreadLocalFormat.get().format(date); }}

这里的DateUtil.formatDate()就是线程安全的了。

参考:

转载地址:https://blog.csdn.net/yzpbright/article/details/106242066 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java核心技术卷一 14.5.12 线程局部变量
下一篇:Java并发编程之死锁的产生以及如何避免死锁

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月03日 00时20分59秒