ThreadLocal (18)

本文详细解析ThreadLocal类的实现机制,包括其内部构造、使用方法及线程安全特性。通过实例演示ThreadLocal如何在多线程环境下为每个线程提供独立的数据存储空间,避免了全局变量带来的问题。




ThreadLocal class UML



ThreadLocal 的源代码

// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)

#ifndef MUDUO_BASE_THREADLOCAL_H
#define MUDUO_BASE_THREADLOCAL_H

#include <boost/noncopyable.hpp>
#include <pthread.h>

namespace muduo
{

template<typename T>
class ThreadLocal : boost::noncopyable
{
 public:
     //构造函数,创建pkey
  ThreadLocal()
  {
     /*
     创建的键存放在pkey指定的内存单元,这个键可以被进程中的所有线程使用,但每个线程
把这个键与不同的线程 “私有数据地址” 进行关联。创建新键时,每个线程的数据地址设为NULL值。    
    ThreadLocal::destructor键的虚构函数    
     **/
    pthread_key_create(&pkey_, &ThreadLocal::destructor);
  }

  ~ThreadLocal()
  {
    pthread_key_delete(pkey_);
  }
    // 获取数据,如果数据还没有,则新建一个
  T& value()
  {
    T* perThreadValue = static_cast<T*>(pthread_getspecific(pkey_));
    if (!perThreadValue) {
      T* newObj = new T();
      //pthread_setspecific使pkey 和 私有数据进行关联
      pthread_setspecific(pkey_, newObj);
      perThreadValue = newObj;
    }
    return *perThreadValue;
  }

 private:

  static void destructor(void *x)
  {
    T* obj = static_cast<T*>(x);
    //判断是否为全类型,如果是则delete obj,
    typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
    delete obj;
  }

 private:
  pthread_key_t pkey_;
};

}
#endif


ThreadLocal 的测试程序

#include <muduo/base/ThreadLocal.h>
#include <muduo/base/CurrentThread.h>
#include <muduo/base/Thread.h>

#include <boost/noncopyable.hpp>
#include <stdio.h>

class Test:boost::noncopyable
{
private :
    std::string name_;
public :
    Test(){
        printf("tid=%d,constructing %p\n",muduo::CurrentThread::tid(),this);

    }   
    ~Test(){
        printf("tid= %d,destructing %p %s\n",muduo::CurrentThread::tid(),this,name_.c_str());
    }

    const std::string &name()const{ return name_ ;}
    void setName(const std::string &n ){ name_ = n ;}

};

muduo::ThreadLocal<Test> testObj1;
muduo::ThreadLocal<Test> testObj2;

void print(){
    printf("tid =%d\tobj1 %p\tname=%s\n",muduo::CurrentThread::tid(),
        &testObj1.value(),
        testObj1.value().name().c_str());
    printf("tid=%d\tobj2 %p name=%s\n",
        muduo::CurrentThread::tid(),
        &testObj2.value(),
        testObj2.value().name().c_str());
}

void threadFunc(){
    print();
    testObj1.value().setName("changed 1") ;
    testObj2.value().setName("changed 2");
    print();

}
int main (void ){
    testObj1.value().setName("main One");
    print();
    muduo::Thread t1 (threadFunc) ;
    t1.start();
    t1.join();
    testObj2.value().setName("main two" ) ;
    print();
    pthread_exit(0);
    return  0 ;

}

程序输出:

[root@localhost bin]# ./threadlocal_test 
tid=2915,constructing 0x9435028
tid =2915   obj1 0x9435028  name=main One
tid=2915,constructing 0x9435038
tid=2915    obj2 0x9435038 name=
tid=2916,constructing 0xb6c00468
tid =2916   obj1 0xb6c00468 name=
tid=2916,constructing 0xb6c00478
tid=2916    obj2 0xb6c00478 name=
tid =2916   obj1 0xb6c00468 name=changed 1
tid=2916    obj2 0xb6c00478 name=changed 2
tid= 2916,destructing 0xb6c00468 changed 1
tid= 2916,destructing 0xb6c00478 changed 2
tid =2915   obj1 0x9435028  name=main One
tid=2915    obj2 0x9435038 name=main two
tid= 2915,destructing 0x9435028 main One
tid= 2915,destructing 0x9435038 main two
[root@localhost bin]# ls



<think>我们正在讨论Spring框架中ThreadLocal的使用场景。根据用户提供的引用,虽然引用内容主要涉及Spring Core和Spring Security等基础模块,但并未直接说明ThreadLocal的使用。不过,结合Spring框架的常见实现,我们可以总结出ThreadLocal在Spring中的几个关键应用场景。 注意:用户提供的引用[1][2][3]主要介绍Spring Core容器和核心功能,引用[4]则提到Spring Security的核心组件。因此,我们需要结合Spring框架的实际实现来回答。 以下是Spring框架中使用ThreadLocal的主要组件和场景: ### 一、Spring事务管理(Transaction Management) 在Spring的事务管理中,`TransactionSynchronizationManager`类使用ThreadLocal来保存当前事务的相关资源(如数据库连接),确保同一个线程内的方法可以共享同一个事务上下文。 **关键ThreadLocal变量**: ```java public abstract class TransactionSynchronizationManager { private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<>("Transactional resources"); private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal<>("Transaction synchronizations"); private static final ThreadLocal<String> currentTransactionName = new NamedThreadLocal<>("Current transaction name"); // 其他省略... } ``` - **作用**:在同一线程中传播事务上下文,避免显式传递连接对象[^1][^3]。 ### 二、请求上下文(Request Context) - 如Spring MVC 在Web应用中,Spring的`RequestContextHolder`使用ThreadLocal来存储当前请求的上下文信息(如HttpServletRequest和HttpServletResponse),以便在Controller、Service层等任何地方都能访问当前请求。 **实现代码**: ```java public abstract class RequestContextHolder { private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>("Request attributes"); // 其他方法... } ``` - **使用场景**:在拦截器或Controller中,可通过`RequestContextHolder.currentRequestAttributes()`获取当前请求[^1]。 ### 三、Spring Security安全上下文(Security Context) Spring Security通过`SecurityContextHolder`将当前认证信息(如用户凭证)绑定到线程。 **ThreadLocal策略**: ```java public class SecurityContextHolder { public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; private static SecurityContextHolderStrategy strategy; // 默认使用ThreadLocalSecurityContextHolderStrategy static { initialize(); } private static void initialize() { // 默认策略为ThreadLocal setStrategyName(MODE_THREADLOCAL); } } ``` - **作用**:在同一个线程中,任何地方都可以通过`SecurityContextHolder.getContext()`获取当前用户的安全上下文[^4]。 ### 四、本地化上下文(LocaleContext) Spring的国际化支持中,`LocaleContextHolder`使用ThreadLocal保存当前请求的本地化信息(Locale)和时区(TimeZone)。 **实现**: ```java public abstract class LocaleContextHolder { private static final ThreadLocal<LocaleContext> localeContextHolder = new NamedThreadLocal<>("Locale context"); // ... } ``` ### 五、其他场景 1. **OpenSessionInViewFilter**(已不推荐): - 在Hibernate中,该过滤器通过ThreadLocal将一个Hibernate Session绑定到整个请求线程,确保延迟加载在视图渲染时仍有效(但此模式存在争议,现代应用推荐使用DTO模式)。 2. **异步任务上下文传递**: - 在Spring 4.3+中,`TaskDecorator`接口可用于将ThreadLocal绑定的上下文(如安全上下文)从父线程传递到子线程。 --- ### 总结:Spring中ThreadLocal的核心作用 | 组件/类 | ThreadLocal用途 | 所在模块 | |--------------------------|-----------------------------------------|-------------------| | `TransactionSynchronizationManager` | 管理事务资源(连接、同步等) | Spring-TX | | `RequestContextHolder` | 存储当前HTTP请求的上下文 | Spring-Web | | `SecurityContextHolder` | 保存当前认证用户的安全上下文 | Spring-Security | | `LocaleContextHolder` | 保存本地化信息(语言、时区) | Spring-Context | > **最佳实践提示**: > 1. 这些组件都使用`static final`修饰ThreadLocal变量,确保全局唯一[^1][^2] > 2. 在Web应用中,需配合过滤器(Filter)或拦截器(Interceptor)及时清理ThreadLocal(如`SecurityContextPersistenceFilter`会在请求结束时清除安全上下文)[^4] --- ### §§相关问题§§ 1. Spring Security中如何将安全上下文传递给子线程? 2. Spring事务管理是如何实现事务传播的? 3. 如何自定义ThreadLocal变量在Spring中的生命周期管理? 4. 为什么OpenSessionInViewFilter被认为是不良实践?</think>### Spring框架中ThreadLocal的核心应用场景 Spring框架在多处关键组件中使用了ThreadLocal来实现线程隔离的上下文管理,以下是主要应用场景及实现原理: --- #### 一、请求上下文管理(Request Context) **核心组件**:`RequestContextHolder` **实现方式**: ```java public abstract class RequestContextHolder { // 使用ThreadLocal存储请求属性 private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>("Request attributes"); // 获取当前请求上下文 public static RequestAttributes currentRequestAttributes() { return requestAttributesHolder.get(); } } ``` **作用**: 在Web请求处理链中(如Controller、Service层),通过`RequestContextHolder`可随时获取当前HTTP请求的`HttpServletRequest`和`HttpServletResponse`对象,实现请求级数据共享[^1][^3]。 **典型使用场景**: ```java // 在任意业务层获取当前请求 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); ``` --- #### 二、事务管理(Transaction Management) **核心组件**:`TransactionSynchronizationManager` **ThreadLocal变量**: ```java public abstract class TransactionSynchronizationManager { // 存储事务资源(如数据库连接) private static final ThreadLocal<Map<Object, Object>> resources = new NamedThreadLocal<>("Transactional resources"); // 存储事务同步器 private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations = new NamedThreadLocal<>("Transaction synchronizations"); } ``` **作用**: 1. 在声明式事务(`@Transactional`)中绑定数据库连接到当前线程 2. 确保同一线程内多个数据库操作使用同一个连接 3. 实现事务的传播行为(如`PROPAGATION_REQUIRED`)[^1][^3] --- #### 三、安全上下文(Security Context) **核心组件**:`SecurityContextHolder` **实现策略**: ```java public class SecurityContextHolder { // 默认使用ThreadLocal存储策略 private static SecurityContextHolderStrategy strategy; static { initialize(); // 初始化时选择MODE_THREADLOCAL策略 } public static SecurityContext getContext() { return strategy.getContext(); // 从ThreadLocal获取 } } ``` **作用**: 存储当前认证用户信息(`Authentication`对象),使`SecurityContext`在请求处理线程中随处可访问[^4]。 **使用示例**: ```java Authentication auth = SecurityContextHolder.getContext().getAuthentication(); ``` --- #### 四、本地化上下文(Locale Context) **核心组件**:`LocaleContextHolder` **实现方式**: ```java public abstract class LocaleContextHolder { private static final ThreadLocal<LocaleContext> localeContextHolder = new NamedThreadLocal<>("Locale context"); // 设置当前线程的Locale public static void setLocale(Locale locale) { setLocaleContext(locale != null ? new SimpleLocaleContext(locale) : null); } } ``` **作用**: 管理国际化(i18n)相关的语言环境,确保同一请求中保持一致的本地化设置[^1]。 --- ### ThreadLocal在Spring中的设计特点 1. **静态化声明** 所有ThreadLocal实例均使用`static final`修饰,确保全局唯一性: ```java private static final ThreadLocal<...> holder = ...; ``` 2. **命名化封装** 使用`NamedThreadLocal`增强可读性和调试能力: ```java new NamedThreadLocal<>("Transactional resources"); ``` 3. **生命周期管理** 通过过滤器/拦截器确保资源清理: ```java // 示例:在Spring Security中清理SecurityContext public class SecurityContextPersistenceFilter { protected void doFilterInternal(...) { try { // 业务处理 } finally { SecurityContextHolder.clearContext(); // 强制清理 } } } ``` --- ### 典型应用模块总结 | 组件模块 | 核心类 | ThreadLocal作用 | 所属Spring模块 | |-------------------------|--------------------------------|-------------------------------------|-------------------| | **请求上下文** | `RequestContextHolder` | 存储HTTP请求/响应对象 | spring-web | | **事务管理** | `TransactionSynchronizationManager` | 绑定数据库连接/事务状态 | spring-tx | | **安全认证** | `SecurityContextHolder` | 存储用户认证信息 | spring-security | | **国际化支持** | `LocaleContextHolder` | 管理语言/时区设置 | spring-context | | **OpenSessionInView** | `SessionFactoryUtils` | 绑定Hibernate Session到请求线程 | spring-orm | > **最佳实践**: > Spring通过`Filter`和`Interceptor`在请求入口初始化ThreadLocal,在出口通过`finally`块调用`remove()`清理资源,避免线程池复用导致的内存泄漏[^1][^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值