- 浏览: 1151199 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (411)
- Java Foundation (41)
- AI/机器学习/数据挖掘/模式识别/自然语言处理/信息检索 (2)
- 云计算/NoSQL/数据分析 (11)
- Linux (13)
- Open Source (12)
- J2EE (52)
- Data Structures (4)
- other (10)
- Dev Error (41)
- Ajax/JS/JSP/HTML5 (47)
- Oracle (68)
- FLEX (19)
- Tools (19)
- 设计模式 (4)
- Database (12)
- SQL Server (9)
- 例子程序 (4)
- mysql (2)
- Web Services (4)
- 面试 (8)
- 嵌入式/移动开发 (18)
- 软件工程/UML (15)
- C/C++ (7)
- 架构Architecture/分布式Distributed (1)
最新评论
-
a535114641:
LZ你好, 用了这个方法后子页面里的JS方法就全不能用了呀
页面局部刷新的两种方式:form+iframe 和 ajax -
di1984HIT:
学习了,真不错,做个记号啊
Machine Learning -
赵师傅临死前:
我一台老机器,myeclipse9 + FB3.5 可以正常使 ...
myeclipse 10 安装 flash builder 4.6 -
Wu_Jiang:
触发时间在将来的某个时间 但是第一次触发的时间超出了失效时间, ...
Based on configured schedule, the given trigger will never fire. -
cylove007:
找了好久,顶你
Editable Select 可编辑select
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").
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/
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://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.
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)
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
发表评论
-
J2SE Evolution
2013-04-11 15:39 1188Java 7 New Features Java SE 7 ... -
未完 Java: IO & NIO(new I/O)
2013-01-11 20:56 2063适用: event and data-driven apps ... -
未完 java设计: naming convention | 命名规范
2012-11-20 16:45 2134应该遵循的规范: 类/接口/属性名,使用名词或形容词 ... -
未完 Java: enum 枚举
2012-11-19 20:29 1826http://stackoverflow.com/que ... -
Java多线程之 concurrent 并发包
2012-11-01 07:47 2028Java Tutorials -> Concur ... -
未完 Java Tips & Tricks & Notes
2012-09-12 10:00 1134Hidden Features of Java: h ... -
未完 Java Socket
2012-09-12 08:42 1025Java SocketJava SocketJava Sock ... -
Java For-each Loop & Iterable | 增强型For循环和Iterable接口
2012-09-11 21:50 2066增强型For循环没什么好说的,Just see link ... -
未完 Java Collections | 容器
2012-09-06 11:35 1842Sources: http://docs.oracle.com ... -
Java object Initialization (class Instantiation) | 对象的初始化(即类的实例化)
2012-09-03 09:12 3012类实例即对象 ... -
未完Java class&interfac 's Loading, Linking and Initializing | 类与接口的加载、链接和初始化
2012-08-31 19:01 1681JVM装载一个类的时候,首先检查他有没有父类,如果有父类则装载 ... -
未完 java Static 总结
2012-08-31 18:47 1408static可以用来修饰: 字段 Fields 方法 Meth ... -
未完 JVM Runtime Data Areas & Java Memory Model | 内存分配模型 & Java数据存储
2012-08-31 18:43 1892Java虚拟机内存分配模型 需精读:Chapter 5 of ... -
Java Data Types & Literals | 数据类型 和 字面量
2012-08-30 18:12 3954Java数据类型划分: OR http:// ... -
未完 Variables 变量 (Instance/Class/Local)
2012-08-29 10:59 1713Local/Instance/Class Variables ... -
未完 Regular Expressions | 正则表达式
2011-08-25 11:43 1532Extended Regular Expression ... -
java Date(util.Date/sql.Date/sql.Timestamp/sql.Time) & Oracle DATE Type 时分秒 精度问题
2011-05-17 09:32 3972遇到的问题描述: 数据库为Oracle,其jdbc驱动为ojd ... -
Java byte code (bytecode)
2011-05-04 02:55 3891keys: bytecode, byte code, opco ... -
Java Classloading Mechanism : ClassLoader & ASM & 动态字节码增强
2011-04-21 13:29 2431Setting the class path: http:// ... -
class literal & instance.getClass() & Class.forName(String className)
2011-04-20 12:33 2344常用的几种取得Class类实例的方式: 1 class lit ...
相关推荐
ThreadLocal 整理 ThreadLocal 是 Java 中的一个重要组件,它能够在每个线程中保持独立的副本。这个功能是通过 Thread 类中的 threadLocals 属性来实现的,这个属性实际上是一个 Entry 数组,其中的每个 Entry 都...
**线程局部变量(ThreadLocal)是Java编程中一个非常重要的工具类,它在多线程环境下提供了线程安全的数据存储。ThreadLocal并不是一个变量,而是一个类,它为每个线程都创建了一个独立的变量副本,使得每个线程都...
ThreadLocal是Java编程语言中的一个类,用于在多线程环境中提供线程局部变量。它是一种特殊类型的变量,每个线程都有自己的副本,互不影响,从而实现线程间数据隔离。ThreadLocal通常被用来解决线程共享数据时可能...
在 `LeakingServlet` 的 `doGet` 方法中,如果 `ThreadLocal` 没有设置值,那么会创建一个新的 `MyCounter` 并设置到 `ThreadLocal` 中。关键在于,一旦 `MyCounter` 被设置到 `ThreadLocal`,那么它将与当前线程...
理解ThreadLocal 理解ThreadLocal 理解ThreadLocal 理解ThreadLocal
Java ThreadLocal详解 ThreadLocal是Java中的一种机制,可以将变量与线程关联起来,使得每个线程都可以拥有自己的变量副本。 ThreadLocal的出现是为了解决多线程编程中的线程安全问题。 从本质上说,ThreadLocal是...
### 正确理解ThreadLocal:深入解析其工作原理与应用场景 #### 一、ThreadLocal的基本概念 `ThreadLocal`是Java平台提供的一种线程局部变量的解决方案,它为每一个使用该变量的线程都提供了独立的变量副本,使得每...
Java中的ThreadLocal是一个非常重要的工具类,它在多线程编程中扮演着独特角色,尤其在处理线程间数据隔离和共享时。ThreadLocal不是线程本身,而是为每个线程提供一个独立的变量副本,使得每个线程都可以独立地改变...
Java事务和ThreadLocal是两种在Java编程中至关重要的概念,它们分别用于处理多线程环境下的数据一致性问题和提供线程局部变量。 首先,我们来深入理解Java事务。在数据库操作中,事务是一系列操作的集合,这些操作...
### Java中ThreadLocal详解 #### 一、ThreadLocal概述 在Java多线程编程中,`ThreadLocal`是一个非常重要的工具类,它提供了一种在每个线程内部存储线程私有实例的方法。通常情况下,当多个线程共享某个变量时,...
ThreadLocal是Java编程中一种非常特殊的变量类型,它主要用于在多线程环境下为每个线程提供独立的变量副本,从而避免了线程间的数据共享和冲突。然而,ThreadLocal在理解和使用过程中容易产生一些误区,这里我们将...
**线程局部变量(ThreadLocal)** 在Java编程中,`ThreadLocal`是一个非常重要的工具类,它用于在多线程环境中提供线程安全的局部变量。`ThreadLocal`并不是一个线程,而是一个线程局部变量的容器,每个线程都有自己...
本资料主要聚焦于两种设计模式以及Java中的ThreadLocal特性。 首先,我们来探讨单例模式。单例模式是一种确保一个类只有一个实例,并提供全局访问点的设计模式。在Java中,通常通过私有构造函数、静态工厂方法或...
学习ThreadLocal,了解其中的原理,以及学习其中的优点!避免坑点!!
**线程局部变量(ThreadLocal)是Java编程中一个非常重要的概念,主要用于在多线程环境中为每个线程提供独立的变量副本。ThreadLocal不是一种数据结构,而是一种解决线程间共享数据的方式,它提供了线程安全的局部...
ThreadLocal是Java编程语言中的一个线程局部变量类,它为每个线程提供了一个独立的变量副本,使得每个线程可以独立地改变自己的副本,而不会影响其他线程所对应的副本。这个特性在多线程环境下处理并发问题时非常...
在Java编程中,ThreadLocal是线程局部变量的类,它提供了一种在多线程环境中为每个线程创建和维护独立副本的机制。ThreadLocal主要用于解决线程间的数据隔离问题,确保各线程拥有自己的变量副本,避免了数据共享带来...