In a previous post, I wrote the usage and benefits of ThreadLocal based instance variables in concurrent applications. This seemingly innocent and fail-proof implementation will provide clear data separation and visibility between threads in multi-threaded applications UNTIL, you use Thread Pooling.
 
ThreadLocal variables as the name suggest is local to the thread, til the thread is alive the ThreadLocal instance variable can not be Garbage Collected. This post explains the theory clearly.
 
To see it in action I wrote a small program which infinitely creates Tasks in one implementation submitting tasks to a Thread Pool and in another instance creating ad-hoc Threads which are no pooled. And I used jVisualVM to monitor the VM.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class ThreadLocalTest { private static ExecutorService executor = Executors.newFixedThreadPool(100); public static void main(String[] args) {
while(true) {
// Thread Pooled based implementation
executor.execute(new SimpleThread());
// Ad-hoc Thread based implementation
new SimpleThread().start();
}
} public static class SimpleThread extends Thread { private ThreadLocal<Integer> no = new ThreadLocal<Integer>() { @Override
protected Integer initialValue() {
return 0;
} }; public void run() {
while(no.get() < 100) {
no.set(no.get() + 1);
}
System.out.println(String.format("Thread : %s Finished", Thread.currentThread().getName()));
no.remove();
}
}
}
In the Thread pooled implementation one thread throwing an Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Thread Name" is just a matter of time.
 
Where as the adhoc Thread creation seems to keep on running with good VM Garbage Collection but the Thread pool implementation fills up the heap space within minutes and eventually runs out of memory. 
 
Lesson
 
Always keep an eye on the Thread classes you use in your application, make sure they don't have ThreadLocal variables when you are using Thread Pooling.

Give special care when you get pre-compiled third-party libraries which might have ThreadLocal so always read javadocs thoroughly when you use Thread pooling.

转载自:http://shazsterblog.blogspot.com/2015/01/anti-pattern-threadlocal-variables-with.html

Anti Pattern - ThreadLocal variables with Thread Pool(转)的更多相关文章

  1. The CLR's Thread Pool

    We were unable to locate this content in zh-cn. Here is the same content in en-us. .NET The CLR's Th ...

  2. Improve Scalability With New Thread Pool APIs

    Pooled Threads Improve Scalability With New Thread Pool APIs Robert Saccone Portions of this article ...

  3. mysql thread pool

    转自:http://blog.csdn.net/wyzxg/article/details/8258033 mysql 线程处理流程图: Mysql支持单线程和多线程两种连接线程模式,如果单线程,则在 ...

  4. Thread pool引起的程序连接数据库响应慢

    数据库版本:percona-mysql 5.6.16 ​在很长一段时间,都会出现程序连接数据库,出现响应慢的情况,正常在几到几十毫秒之间,但是偶尔会出现上百毫秒的情况: 开始由于开发重新设置并调整过程 ...

  5. Reporting Service 告警"w WARN: Thread pool pressure. Using current thread for a work item"

    如果Reporting Service偶尔出现不可访问或访问出错情况,这种情况一般没有做监控的话,很难捕捉到.出现这种问题,最好检查Reporting Service的日志文件. 今天早上就遇到这样一 ...

  6. MySQL thread pool【转】

    本文来自:http://blog.chinaunix.net/uid-26896862-id-3993773.html 刚刚经历了淘宝的双11,真实感受到了紧张的氛围.尽管DB淡定的度过,但是历程中的 ...

  7. worksteal thread pool

    worksteal的场景 对于一个线程池,每个线程有一个队列,想象这种场景,有的线程队列中有大量的比较耗时的任务堆积,而有的线程队列却是空的,现象就是有的线程处于饥饿状态,而有的线程处于消化不良的状态 ...

  8. CLR thread pool

    Thread Pooling https://msdn.microsoft.com/en-us/library/windows/desktop/ms686756(v=vs.85).aspx Threa ...

  9. MySQL Thread Pool: Problem Definition

    A new thread pool plugin is now a part of the MySQL Enterprise Edition.In this blog we will cover th ...

随机推荐

  1. Flask - 四剑客 | templates | 配置文件 | 路由系统 | CBV

    Flask框架简介 说明:flask是一个轻量级的web框架,被称为微型框架.只提供了一个高效稳定的核心,其它全部通过扩展来实现.意思就是你可以根据项目需要进行量身定制,也意味着你需要不断学习相关的扩 ...

  2. C语言实验二——位运算

    问题 线性反馈移位寄存器 Linear feedback shift register(LFSR),是指给定前一状态,将该输出的线性函数再用作输入的移位寄存器.异或运算是最常见的单比特线性函数:对寄存 ...

  3. pycharm注册使用

    先在PyCharm官网下载安装包 链接:https://www.jetbrains.com/pycharm/download/#section=linux 选择平台为Linux,可以看到当前版本为20 ...

  4. Mysql 查询阻塞和事物情况

    MYSQL 服务器逻辑架构图 连接/线程处理 == > (解析器 –> 查询缓存) ===> 优化器 ===> 存储引擎 服务器级别锁MYSQL 使用的锁类型:表锁(显式:LO ...

  5. loj #6485. LJJ 学二项式定理 单位根反演

    新学的黑科技,感觉好nb ~ #include <bits/stdc++.h> #define ll long long #define setIO(s) freopen(s". ...

  6. C语言malloc的用法及详解

    #include <stdio.h> #include <stdlib.h> void freem(int* p){ #include <stdio.h> #inc ...

  7. 行列式的组合定义及其应用--反对称阵的Pfaffian

    以组合定义为出发点的行列式理论的引入方式在很多高等代数或线性代数的教材中被采用, 其优缺点同样明显. 组合定义形式上的简单是其最大的优点, 用它可以简洁地证明行列式的所有性质, 并快速进入行列式的计算 ...

  8. 一步HTML5教程学会体系

    HTML5是HTML最新的版本,万维网联盟. HTML5是下一代的HTML标准,HTML5是为了在移动设备上支持多媒体. 新特性: 绘画的canvas元素,用于媒介回放的video和audio元素,对 ...

  9. FLUENT求解传热系数surfaceheattransfercoef.的参考值的设置【转载】

    转载自:http://blog.sina.com.cn/s/blog_7ef78d170101ch30.html surface heat transfer coef. 计算公式: FLUENT求解传 ...

  10. GO获取随机数

    使用的"math/rand"包. 基本随机数 a := rand.Int() b := rand.Intn(100) //生成0-99之间的随机数 fmt.Println(a) f ...