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. HDU - 3709 - Balanced Number(数位DP)

    链接: https://vjudge.net/problem/HDU-3709 题意: A balanced number is a non-negative integer that can be ...

  2. 基于Python3+Requests的贴吧签到助手

    因为总是忘记签到,所以尝试写了一个签到脚本,因为使用的是Python3,所以没法使用Urllib2,于是选择了Requests,事实证明,Requests比Urllib2好用.整体思路比较简单,就是模 ...

  3. 【Python数据挖掘】第三篇--Numpy 和 可视化

    一.Numpy 数组是一系列同类型数据的集合,可以被非零整数进行索引,可以通过列表进行数组的初始化,数组也可以通过索引进行切片. Numpy提供了几乎全部的科学计算方式. # numpy 导入方式: ...

  4. javascript之大文件分段上传、断点续传

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  5. C# 对IOC的理解 依赖的转移

    原文:https://blog.csdn.net/huwei2003/article/details/40022011 系统 可方便的替换 日志类 自己的理解: 依赖接口,日志的实例化 不直接写在依赖 ...

  6. 洛谷P5017摆渡车

    题目 一道做法多种多样的题,DP做法的状态也很多. 我用\(dp[i]\)表示在第i秒发车的时间和,然后dp方程就很好写了 \(dp[i] = dp[j] + i车的等待时间\)j属于i-2m ~ i ...

  7. [代码审计]php反序列化漏洞

    0x01 php面向对象简介 对象:可以对其做事情的一些东西.一个对象有状态.行为和标识三种属性. 类:一个共享相同结构和行为的对象的集合. 每个类的定义都以关键字class开头,后面跟着类的名字. ...

  8. SpringMVC从Session域中获取值

    SpringMVC从Session域中获取值 SpringMVC环境自行搭建 第一步:前端页面 第二步.后台代码 第三步.响应视图 第四步.在当前处理器所在的类设置@SessionAttributes ...

  9. python 嵌套字典取值增强版

    def getdictvalue(d,code): result=[] if isinstance(d, dict) : try: value = d[code] result.append(valu ...

  10. python判断字符串包含关系

    转自---http://blog.csdn.net/yl2isoft/article/details/52079960 1.使用成员操作符 in >>> s='nihao,shiji ...