`
阅读更多
  
ThreadLocal 可以理解成 Current Thread Context 或 Current Thread Local Variable。

http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/
http://javarevisited.blogspot.com/2012/05/how-to-use-threadlocal-in-java-benefits.html
引用
ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there is no choice other than synchronize if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn't address synchronization requirement, instead it eliminates sharing by providing explicitly copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of application.


When and how should I use a ThreadLocal variable?
http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable
引用
Since a ThreadLocal is a reference to data within a given Thread, you can end up with classloading leaks when using ThreadLocals in application servers which use thread pools. You need to be very careful about cleaning up any ThreadLocals you get() or set() by using the ThreadLocal's remove() method.

Many frameworks use ThreadLocals to maintain some context related to the current thread. For example when the current transaction is stored in a ThreadLocal, you don't need to pass it as a parameter through every method call, in case someone down the stack needs access to it. Web applications might store information about the current request and session in a ThreadLocal, so that the application has easy access to them. With Guice you can use ThreadLocals when implementing custom scopes for the injected objects (Guice's default servlet scopes most probably use them as well).
ThreadLocals are one sort of global variables (although slightly less evil because they are restricted to one thread), so you should be careful when using them to avoid unwanted side-effects and memory leaks. Design your APIs so that the ThreadLocal values will always be automatically cleared when they are not anymore needed and that incorrect use of the API won't be possible (for example like this). ThreadLocals can be used to make the code cleaner, and in some rare cases they are the only way to make something work (my current project had two such cases; they are documented here under "Static Fields and Global Variables").



Why is java.lang.ThreadLocal a map on Thread instead on the ThreadLocal?
http://stackoverflow.com/questions/1829046/why-is-java-lang-threadlocal-a-map-on-thread-instead-on-the-threadlocal?rq=1






ThreadLocal + Thread pool: (thread pool 参见:http://wuaner.iteye.com/blog/1709915)
同时使用 ThreadLocal 和 Thread pool 不是一个好的设计方案!不要试图用 InheritableThreadLocal 向 reused ThreadPool 中 传递 threadlocal vars!In most containers, threads are reused via thread pools and thus are never gc. this would lead something wired。
原因:
http://www2.sys-con.com/itsg/virtualcd/java/archives/0711/goenka/index.html
引用
Thread Pooling Breaks Usage of Thread-Local Variables
Thread pooling is not friendly to the java.lang.ThreadLocal and java.lang.InheritableThreadLocal classes that were introduced in JDK 1.2 to provide thread-local variables. These variables differ from other variables in that each thread has its own independently initialized copy of the variable. The typical usage of a thread-local variable in a multithreaded application is to keep track of some application context associated with the request, such as the identity of the user making the request. The get() and set() methods in the ThreadLocal class return and set the value that corresponds to the executing thread. Thus, each thread executing a get() on a given ThreadLocal variable can potentially get a different object. The set() similarly allows each executing thread to set a different value for the same ThreadLocal variable.
http://www.cxyclub.cn/n/28026/
http://stackoverflow.com/questions/7403809/java-cached-thread-pool-and-thread-local
http://stackoverflow.com/questions/9012371/using-inheritablethreadlocal-with-threadpoolexecutor-or-a-threadpoolexecut?lq=1
避免问题的方法:
1 不要重用 Thread pool 中的线程,每次都建立新的(即,不要将 Thread poll,如 ExecutorService 设为成员变量,而作为 局部变量 使用):
http://stackoverflow.com/questions/18129039/thread-pooling-and-inheritedthreadlocal
我们使用 Thread pool 的原因就是为了重用线程池中线程,以达到最小的线程创建/销毁的开销;所以,尽管这种方式可以避免 ThreadLocal + Thread pool 的问题,但不是一个好的解决办法。



同样的道理,在tomcat 等web container 中,为了性能的需要,也存在 request thread pool(如 tomcat 默认的大小为 200);既然存在 thread reuse,那当在这些web container中使用 ThreadLocal 时也会存在上面的问题。解决办法:
1 使用 servlet Filter 在每次访问请求前清理当前 thread 中的threadlocal:
http://luchinkup.blogspot.com/2005/06/threadlocal-rocks-and-dont-let-em-tell.html



ThreadLocal 与 内存泄露:
http://dave.srednal.com/archives/14



ThreadLocal 的 remove() 和 set(null) 的区别是什么?
http://stackoverflow.com/questions/12424838/threadlocal-remove



对非线程安全的对象如 SimpleDateFormat,使用 ThreadLocal 来确保线程安全是个不错的选择:
http://stackoverflow.com/questions/4107839/synchronizing-access-to-simpledateformat
引用
三种方式确保 的线程安全:
Option 1: Create local instances when required
Option 2: Create an instance of SimpleDateFormat as a class variable but synchronize access to it.
Option 3: Create a ThreadLocal to store a different instance of SimpleDateFormat for each thread.
各自的好坏:
1. Creating SimpleDateFormat is expensive. Don't use this unless it's done seldom.
2. OK if you can live with a bit of blocking. Use if formatDate() is not used much.
3. Fastest option IF you reuse threads (thread pool). Uses more memory than 2. and has higher startup overhead.

For applications both 2. and 3. are viable options. Which is best for your case depends on your use case. Beware of premature optimization. Only do it if you believe this is an issue.

For libraries that would be used by 3rd party I'd use option 3.



ThreadLocal explained:
http://doanduyhai.wordpress.com/2011/12/04/threadlocal-explained/
引用
A ThreadLocal object is created, then attached to the current thread. All portion of your program executed by the current thread can access the ThreadLocal target Object, provided that the code can access the ThreadLocal reference, and that’s the trick! There is no point creating a ThreadLocal if it cannot be accessed everywhere in your code.
Most of the time, the ThreadLocal object itself is created as a static final variable. Static to make it accessible from everywhere and final to avoid being modified. There is no need to synchronize the access to the ThreadLocal object itself since only the target Object is usefull and this object is different from one thread to another (so thread-safe by nature)
public class ThreadLocalTest implements Runnable {

    private static final ThreadLocal<String> threadLocal = new ThreadLocal<String>();

    private String value;
    private long delayTime;
    private long sleepTime;

    public ThreadLocalTest(String value, long delayTime, long sleepTime) {
        this.value = value;
        this.delayTime = delayTime;
        this.sleepTime = sleepTime;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(this.delayTime);
            System.out.println("[" + Thread.currentThread().getName() + "] is setting value [" + this.value + "] to [" + threadLocal + "]");
            threadLocal.set(this.value);
            Thread.sleep(this.sleepTime);
            System.out.println("[" + Thread.currentThread().getName() + "] is accessing value [" + threadLocal.get() + "] from [" + threadLocal + "]");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ThreadLocalTest test1 = new ThreadLocalTest("V1", 0, 200);
        ThreadLocalTest test2 = new ThreadLocalTest("V2", 100, 500);
        Thread t1 = new Thread(test1, "thread1");
        Thread t2 = new Thread(test2, "thread2");

        t1.start();
        t2.start();
    }

}



InheritableThreadLocal:
使用之,可以让当前线程其子线程也共享 InheritableThreadLocal 内的数据。


Srcs:
正确理解ThreadLocal:
http://www.iteye.com/topic/103804
ThreadLocal的几种误区
http://www.blogjava.net/jspark/archive/2006/08/01/61165.html
分享到:
评论

相关推荐

    ThreadPoolExecutor源码解析.pdf

    - **TIDYING**:整理状态,所有任务已执行完毕,无工作线程,执行terminated方法后进入TERMINATED状态。 - **TERMINATED**:终止状态,线程池完全终止,所有资源被释放。 2. **核心数据结构** - **BlockingQueue...

    IT互联网名企经典面试题汇总:Java篇 (2).docx

    6. **ThreadLocal**:ThreadLocal为每个线程提供了独立的变量副本,避免了多线程环境下数据共享带来的问题。 7. **聚簇索引与非聚簇索引**:聚簇索引决定了数据的物理存储顺序,而非聚簇索引不决定数据的物理顺序,...

    毕业设计-程序 思创兼职V6.6.5 全开源版-整站商业源码.zip

    毕业设计-程序 思创兼职V6.6.5 全开源版-整站商业源码.zip

    配电网电压与无功优化协调:基于二阶锥规划的多目标函数及场景分析

    内容概要:本文探讨了配电网电压与无功协调优化的问题,旨在通过优化手段最小化运行成本并减少电压偏差。文中介绍了目标函数的构成,包括开关动作成本、功率损耗成本和设备运行成本,并提出了将非凸模型转化为二阶锥规划模型的方法。通过优化变压器分接头位置、电容器接入组数以及SOP的输出功率,实现了电压与无功的有效控制。此外,还对不同场景进行了对比分析,验证了优化策略的效果。 适合人群:从事电力系统研究、配电网管理和优化的专业人士,以及对电力系统优化感兴趣的学者和技术人员。 使用场景及目标:适用于希望深入了解配电网电压与无功协调优化的技术人员,帮助他们掌握优化策略的具体应用,提升电网运行效率和稳定性。 其他说明:文章不仅提供了理论分析,还涉及了具体的模型构建和优化算法实现,有助于读者全面理解配电网优化的实际操作流程。

    毕业设计-红包拓客生意宝V1.6.44 开源版-整站商业源码.zip

    毕业设计-红包拓客生意宝V1.6.44 开源版-整站商业源码.zip

    外转子无刷直流电机温度场特性分析与瞬态热仿真的关键技术及应用

    内容概要:本文详细探讨了外转子无刷直流电机在不同应用场景(如无人机、电动车轮毂)中的温度场特性及其瞬态热仿真方法。首先介绍了电机的主要热源(铜损和铁损),并通过Python代码实现了铜损的精确计算。接着讨论了建模过程中散热边界的设定,特别是在外转子结构中利用ANSYS Fluent进行风冷仿真时需要注意的问题。文中还强调了对流换热系数的合理估算以及瞬态仿真中时间步长的优化设置。最后,通过Python后处理工具生成温度变化曲线,并提供了仿真结果与实际情况不符时的排查建议。 适合人群:从事电机设计、制造及相关领域的工程师和技术人员,尤其是对外转子无刷直流电机感兴趣的研究人员。 使用场景及目标:适用于需要深入了解外转子无刷直流电机温度特性和掌握相关热仿真技能的专业人士。目标是提高电机设计的可靠性和性能,避免因温度过高导致的安全隐患。 其他说明:文章不仅提供了理论分析,还包括具体的代码实现和实践经验分享,有助于读者更好地理解和应用所学知识。

    音乐领域千千阙歌词分析:探讨离别情感与回忆的美好表达方式设计

    内容概要:《千千阙歌》是一首表达离别之情的歌曲,歌词描绘了一对恋人即将分离的情景。歌词中充满了对过去美好时光的回忆和对未来重逢的期待,表达了主人公在离别时刻的复杂情感。通过“红红仍是你,赠我的心中艳阳”、“来日纵使千千阕歌,飘于远方我路上”等诗句,传达了即使未来有再多美好的事物,也无法替代此刻与对方共度的美好时光。歌词反复强调“都比不起这宵美丽”,突出了今夜的独特性和珍贵性。; 适合人群:喜欢抒情歌曲或对离别主题感兴趣的听众。; 使用场景及目标:①适合在离别、感伤的场合播放;②用于表达对过去美好时光的怀念;③适用于想要感受深刻情感共鸣的人群。; 阅读建议:这首歌的歌词富有诗意,情感细腻,建议在安静的环境下聆听,细细品味歌词中蕴含的情感,感受那份对美好时光的留恋与不舍。

    实训商业源码-果蔬识别1.0.4-论文模板.zip

    实训商业源码-果蔬识别1.0.4-论文模板.zip

    毕业设计-oa办公-整站商业源码.zip

    毕业设计-oa办公-整站商业源码.zip

    实训商业源码-柚家政6.1.0+分销插件 1.0.2-论文模板.zip

    实训商业源码-柚家政6.1.0+分销插件 1.0.2-论文模板.zip

    毕业设计-付费阅读5.3.9公众号H5版-整站商业源码.zip

    毕业设计-付费阅读5.3.9公众号H5版-整站商业源码.zip

    MPU6050姿态角解算:二维卡尔曼滤波与DMP引擎方法解析及其应用

    内容概要:本文详细介绍了MPU6050姿态角解算程序的两种主要方法——二维卡尔曼滤波和自带DMP引擎。首先阐述了传感器技术的发展背景下,姿态角解算的重要性和必要性。接着分别讲解了二维卡尔曼滤波的原理、实现步骤以及其特点,强调了它在处理环境噪声和测量噪声方面的优势。然后讨论了自带DMP引擎的姿态角解算程序,指出其直接优化的方式和适用于高精度、实时性强的应用场景。最后总结了两种方法的选择依据,并展望了未来的发展趋势。 适合人群:从事嵌入式系统开发、机器人工程、自动化控制等领域并对姿态角解算感兴趣的工程师和技术爱好者。 使用场景及目标:帮助开发者理解并选择最适合自身项目的姿态角解算方法,特别是在无人驾驶、无人机飞行控制等对精度和实时性有较高要求的应用场景中。 其他说明:文中不仅提供了理论知识,还涉及到了具体的实现细节,有助于读者更好地理解和应用相关技术。

    MATLAB仿真实现Chan法计算TDOA与GDOP评估——无线定位技术研究

    内容概要:本文详细介绍了使用MATLAB进行无线定位技术的研究,重点在于利用Chan法计算TDOA(到达时间差)和GDOP(几何精度稀释因子)。首先解释了TDOA的概念及其在无线定位系统中的重要性,展示了如何通过MATLAB代码实现Chan法计算TDOA的具体步骤。接着阐述了GDOP作为衡量定位系统几何精度的重要指标,演示了不同接收器和信号源位置下GDOP值的计算方法。最后,通过对仿真结果的分析,加深了对无线定位技术原理的理解,并指出了实践中可能遇到的问题和挑战。 适合人群:对无线定位技术和MATLAB有一定了解的研发人员和技术爱好者。 使用场景及目标:适用于需要深入了解TDOA和GDOP计算原理的研究人员,以及希望通过MATLAB仿真提升实践技能的学习者。 其他说明:文中提供了详细的MATLAB代码片段,帮助读者更好地理解和复现实验过程。同时强调了理论与实践相结合的重要性,鼓励读者尝试调整参数以获得更深的理解。

    毕业论文-烟雨图床v2.1.3正式版源码-整站商业源码.zip

    毕业论文-烟雨图床v2.1.3正式版源码-整站商业源码.zip

    毕业论文-智云物业2.3.9-整站商业源码.zip

    毕业论文-智云物业2.3.9-整站商业源码.zip

    实训商业源码-砍价宝7.2.0开源-论文模板.zip

    实训商业源码-砍价宝7.2.0开源-论文模板.zip

    实训商业源码-超人名片小程序2.0.3 原版-论文模板.zip

    实训商业源码-超人名片小程序2.0.3 原版-论文模板.zip

    异步电机矢量控制技术解析:基于DSP、MCU的FOC实现及转子磁场定向控制

    内容概要:本文深入探讨了异步电机的矢量控制技术,特别是Field Oriented Control (FOC) 和转子磁场定向控制。文章介绍了三种不同的FOC实现方案:基于DSP的高精度控制系统、基于MCU的经济实用系统以及详细的Word文档说明。每种方案都包含了具体的代码片段和技术细节,展示了如何通过空间矢量脉宽调制(SVPWM) 实现电机电流的精确控制。此外,还讨论了转子磁场定向控制的关键技术和应用场景,如工业自动化、机器人和电动汽车等。最后,文章总结了这些系统的出色控制效果,并展望了未来的发展方向。 适合人群:电气工程专业学生、电机控制领域的工程师和技术爱好者。 使用场景及目标:适用于希望深入了解异步电机矢量控制技术的专业人士,旨在帮助他们掌握FOC的具体实现方法和应用场景,提高电机控制的精度和效率。 其他说明:文中提供的代码片段和技术细节有助于读者更好地理解和实践FOC系统的设计与实现。

    永磁同步电机二阶线性与非线性自抗扰控制器(ADRC)的Matlab与Simulink建模及三阶观测器研究

    内容概要:本文深入探讨了永磁同步电机的二阶线性模型及其与非线性自抗扰控制器(ADRC)的结合。首先介绍了永磁同步电机的二阶线性模型,通过微分方程描述电机的关键参数与其机械运动状态的关系。接着阐述了ADRC作为一种先进控制算法,在抑制电机高速运转时的振动和噪声方面的作用。随后讨论了Matlab和Simulink在构建模型和仿真中的应用,使研究人员可以实时观察和调整电机的运行状态。最后引入了三阶观测器,用于提高系统性能和稳定性,提供更准确的状态变量反馈。文中还列举了一些相关领域的权威文献和资料,帮助读者深入了解这一主题。 适合人群:对电机控制系统感兴趣的科研人员、工程师和技术爱好者。 使用场景及目标:适用于需要理解和掌握永磁同步电机控制策略的研究人员,特别是那些希望利用Matlab和Simulink进行建模和仿真的技术人员。目标是提升对永磁同步电机及其控制策略的理解,增强实际工程应用能力。 其他说明:文中提供的示例代码仅作示意,具体实现需根据实际情况调整。此外,文中引用的相关文献有助于读者进一步深入研究。

    抽水蓄能电站最优调度方案研究:基于粒子群算法的混合发电系统经济调度模型

    内容概要:本文详细探讨了抽水蓄能电站在电力系统中的调峰填谷功能,以及如何利用粒子群算法优化其调度策略。文章首先介绍了抽水蓄能电站在电力需求高峰和低谷时的不同角色,强调其对电网稳定性和经济效益的重要性。接着,结合各类电源的调峰电价机制,提出了一个以成本最低为目标的混合发电系统调峰经济调度模型。随后,引入粒子群算法作为优化工具,通过模拟自然群体行为,在解空间中搜索最优解,从而找到最佳调度方案。最后,通过MATLAB仿真验证了该模型的有效性,证明其能在保证电网稳定的同时实现成本最小化。 适合人群:从事电力系统研究、调度管理的专业人士,以及对智能调度技术和粒子群算法感兴趣的科研人员。 使用场景及目标:适用于需要优化抽水蓄能电站调度策略的研究机构和企业,旨在提高电网稳定性并降低成本。 其他说明:随着绿色能源的快速发展和智能电网的推进,抽水蓄能电站在未来将发挥更重要的作用,因此该研究对未来能源发展具有指导意义。

Global site tag (gtag.js) - Google Analytics