- 浏览: 557670 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (340)
- Spring (4)
- Hibernate (2)
- Linux (34)
- Oracle (145)
- Eclipse (1)
- UML (1)
- HTML&&JAVASCRIPT (11)
- JAVA (33)
- 设计模式 (1)
- 版本控制 (1)
- wrap框架 (3)
- IBATIS (5)
- Ruby (1)
- DWR (1)
- MINA (11)
- JBPM (2)
- 缓存技术 (4)
- 网络 (3)
- 应用服务器 (1)
- GWT (5)
- 杂谈 (2)
- ICE (4)
- XML (2)
- ArcGis (2)
- Flex (8)
- junit单元测试 (1)
- SNMP (1)
- 存储 (1)
- office (1)
- MongoDB (0)
- Greenplum (3)
- 管理点滴 (1)
- C++ (6)
- 网络入门 (3)
- Tomcat (7)
- JMX (0)
- webservice (1)
- Oracle的10046事件 (1)
- Library cache内部机制详解 (1)
- expdp通过dblink来导入 (1)
最新评论
-
yuanliangding:
有没有关于mock的更多知识。
基于mock对象和JUnit框架简化Spring Web组件单元测试 -
saup007:
ssh端口不是22,怎么搞呢?
Greenplum 学习笔记 -
springmvc-freemarker:
java开源项目源码实例下载
Apache上全部JAVA开源项目简介 -
bobbell:
哇塞,你真厉害,整理的非常全面。我是一个java barcod ...
Greenplum 学习笔记 -
wsj55133245513324:
这不是bug,你将日志级别从debug提升到INFO 就好了 ...
Spring,smppapi,apache mina, ssl快速实现安全的smpp(5)
首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。
另外,说ThreadLocal使得各线程能够保持各自独立的一个对象,并不是通过ThreadLocal.set()来实现的,而是通过每个线程中的new 对象 的操作来创建的对象,每个线程创建一个,不是什么对象的拷贝或副本。通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象,ThreadLocal实例是作为map的key来使用的。
如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。
下面来看一个hibernate中典型的ThreadLocal的应用:
- private static final ThreadLocal threadSession = new ThreadLocal();
- public static Session getSession() throws InfrastructureException {
- Session s = (Session) threadSession.get();
- try {
- if (s == null) {
- s = getSessionFactory().openSession();
- threadSession.set(s);
- }
- } catch (HibernateException ex) {
- throw new InfrastructureException(ex);
- }
- return s;
- }
private static final ThreadLocal threadSession = new ThreadLocal(); public static Session getSession() throws InfrastructureException { Session s = (Session) threadSession.get(); try { if (s == null) { s = getSessionFactory().openSession(); threadSession.set(s); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } return s; }
可以看到在getSession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap(下面会讲到),而threadSession作为这个值的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。
显然,其他线程中是取不到这个session的,他们也只能取到自己的ThreadLocalMap中的东西。要是session是多个线程共享使用的,那还不乱套了。
试想如果不用ThreadLocal怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,ThreadLocal的实现刚好相反,它是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。
总之,ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点:
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。
ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。
下面来看看ThreadLocal的实现原理(jdk1.5源码)
- public class ThreadLocal<T> {
- /**
- * ThreadLocals rely on per-thread hash maps attached to each thread
- * (Thread.threadLocals and inheritableThreadLocals). The ThreadLocal
- * objects act as keys, searched via threadLocalHashCode. This is a
- * custom hash code (useful only within ThreadLocalMaps) that eliminates
- * collisions in the common case where consecutively constructed
- * ThreadLocals are used by the same threads, while remaining well-behaved
- * in less common cases.
- */
- private final int threadLocalHashCode = nextHashCode();
- /**
- * The next hash code to be given out. Accessed only by like-named method.
- */
- private static int nextHashCode = 0;
- /**
- * The difference between successively generated hash codes - turns
- * implicit sequential thread-local IDs into near-optimally spread
- * multiplicative hash values for power-of-two-sized tables.
- */
- private static final int HASH_INCREMENT = 0x61c88647;
- /**
- * Compute the next hash code. The static synchronization used here
- * should not be a performance bottleneck. When ThreadLocals are
- * generated in different threads at a fast enough rate to regularly
- * contend on this lock, memory contention is by far a more serious
- * problem than lock contention.
- */
- private static synchronized int nextHashCode() {
- int h = nextHashCode;
- nextHashCode = h + HASH_INCREMENT;
- return h;
- }
- /**
- * Creates a thread local variable.
- */
- public ThreadLocal() {
- }
- /**
- * Returns the value in the current thread's copy of this thread-local
- * variable. Creates and initializes the copy if this is the first time
- * the thread has called this method.
- *
- * @return the current thread's value of this thread-local
- */
- public T get() {
- Thread t = Thread.currentThread();
- ThreadLocalMap map = getMap(t);
- if (map != null)
- return (T)map.get(this);
- // Maps are constructed lazily. if the map for this thread
- // doesn't exist, create it, with this ThreadLocal and its
- // initial value as its only entry.
- T value = initialValue();
- createMap(t, value);
- return value;
- }
- /**
- * Sets the current thread's copy of this thread-local variable
- * to the specified value. Many applications will have no need for
- * this functionality, relying solely on the {@link #initialValue}
- * method to set the values of thread-locals.
- *
- * @param value the value to be stored in the current threads' copy of
- * this thread-local.
- */
- public void set(T value) {
- Thread t = Thread.currentThread();
- ThreadLocalMap map = getMap(t);
- if (map != null)
- map.set(this, value);
- else
- createMap(t, value);
- }
- /**
- * Get the map associated with a ThreadLocal. Overridden in
- * InheritableThreadLocal.
- *
- * @param t the current thread
- * @return the map
- */
- ThreadLocalMap getMap(Thread t) {
- return t.threadLocals;
- }
- /**
- * Create the map associated with a ThreadLocal. Overridden in
- * InheritableThreadLocal.
- *
- * @param t the current thread
- * @param firstValue value for the initial entry of the map
- * @param map the map to store.
- */
- void createMap(Thread t, T firstValue) {
- t.threadLocals = new ThreadLocalMap(this, firstValue);
- }
- .......
- /**
- * ThreadLocalMap is a customized hash map suitable only for
- * maintaining thread local values. No operations are exported
- * outside of the ThreadLocal class. The class is package private to
- * allow declaration of fields in class Thread. To help deal with
- * very large and long-lived usages, the hash table entries use
- * WeakReferences for keys. However, since reference queues are not
- * used, stale entries are guaranteed to be removed only when
- * the table starts running out of space.
- */
- static class ThreadLocalMap {
- ........
- }
- }
public class ThreadLocal<T> { /** * ThreadLocals rely on per-thread hash maps attached to each thread * (Thread.threadLocals and inheritableThreadLocals). The ThreadLocal * objects act as keys, searched via threadLocalHashCode. This is a * custom hash code (useful only within ThreadLocalMaps) that eliminates * collisions in the common case where consecutively constructed * ThreadLocals are used by the same threads, while remaining well-behaved * in less common cases. */ private final int threadLocalHashCode = nextHashCode(); /** * The next hash code to be given out. Accessed only by like-named method. */ private static int nextHashCode = 0; /** * The difference between successively generated hash codes - turns * implicit sequential thread-local IDs into near-optimally spread * multiplicative hash values for power-of-two-sized tables. */ private static final int HASH_INCREMENT = 0x61c88647; /** * Compute the next hash code. The static synchronization used here * should not be a performance bottleneck. When ThreadLocals are * generated in different threads at a fast enough rate to regularly * contend on this lock, memory contention is by far a more serious * problem than lock contention. */ private static synchronized int nextHashCode() { int h = nextHashCode; nextHashCode = h + HASH_INCREMENT; return h; } /** * Creates a thread local variable. */ public ThreadLocal() { } /** * Returns the value in the current thread's copy of this thread-local * variable. Creates and initializes the copy if this is the first time * the thread has called this method. * * @return the current thread's value of this thread-local */ public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) return (T)map.get(this); // Maps are constructed lazily. if the map for this thread // doesn't exist, create it, with this ThreadLocal and its // initial value as its only entry. T value = initialValue(); createMap(t, value); return value; } /** * Sets the current thread's copy of this thread-local variable * to the specified value. Many applications will have no need for * this functionality, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current threads' copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } /** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; } /** * Create the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @param firstValue value for the initial entry of the map * @param map the map to store. */ void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } ....... /** * ThreadLocalMap is a customized hash map suitable only for * maintaining thread local values. No operations are exported * outside of the ThreadLocal class. The class is package private to * allow declaration of fields in class Thread. To help deal with * very large and long-lived usages, the hash table entries use * WeakReferences for keys. However, since reference queues are not * used, stale entries are guaranteed to be removed only when * the table starts running out of space. */ static class ThreadLocalMap { ........ } }
可以看到ThreadLocal类中的变量只有这3个int型:
- private final int threadLocalHashCode = nextHashCode();
- private static int nextHashCode = 0;
- private static final int HASH_INCREMENT = 0x61c88647;
private final int threadLocalHashCode = nextHashCode(); private static int nextHashCode = 0; private static final int HASH_INCREMENT = 0x61c88647;
而作为ThreadLocal实例的变量只有 threadLocalHashCode 这一个,nextHashCode 和HASH_INCREMENT 是ThreadLocal类的静态变量,实际上HASH_INCREMENT是一个常量,表示了连续分配的两个ThreadLocal实例的threadLocalHashCode值的增量,而nextHashCode 的表示了即将分配的下一个ThreadLocal实例的threadLocalHashCode 的值。
可以来看一下创建一个ThreadLocal实例即new ThreadLocal()时做了哪些操作,从上面看到构造函数ThreadLocal()里什么操作都没有,唯一的操作是这句:
private final int threadLocalHashCode = nextHashCode();
那么nextHashCode()做了什么呢:
- private static synchronized int nextHashCode() {
- int h = nextHashCode;
- nextHashCode = h + HASH_INCREMENT;
- return h;
- }
private static synchronized int nextHashCode() { int h = nextHashCode; nextHashCode = h + HASH_INCREMENT; return h; }
就是将ThreadLocal类的下一个hashCode值即nextHashCode的值赋给实例的threadLocalHashCode,然后nextHashCode的值增加HASH_INCREMENT这个值。
因此ThreadLocal实例的变量只有这个threadLocalHashCode,而且是final的,用来区分不同的ThreadLocal实例,ThreadLocal类主要是作为工具类来使用,那么ThreadLocal.set()进去的对象是放在哪儿的呢?
看一下上面的set()方法,两句合并一下成为
ThreadLocalMap map = Thread.currentThread().threadLocals;
这个ThreadLocalMap 类是ThreadLocal中定义的内部类,但是它的实例却用在Thread类中:
- public class Thread implements Runnable {
- ......
- /* ThreadLocal values pertaining to this thread. This map is maintained
- * by the ThreadLocal class. */
- ThreadLocal.ThreadLocalMap threadLocals = null;
- ......
- }
public class Thread implements Runnable { ...... /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; ...... }
再看这句:
if (map != null) map.set(this, value);
也就是将该ThreadLocal实例作为key,要保持的对象作为值,设置到当前线程的ThreadLocalMap 中,get()方法同样大家看了代码也就明白了,ThreadLocalMap 类的代码太多了,我就不帖了,自己去看源码吧。
发表评论
-
Apache上全部JAVA开源项目简介
2011-05-12 17:16 1915最近接触Jakarta-Common-BeanU ... -
主题:JAVA NIO 简介
2011-04-15 11:48 9821. 基本 概念 IO 是主存和外部设备 ( 硬盘、终端和 ... -
JNDI在Java EE中的应用
2011-04-01 15:52 1058一、JNDI在Java EE中的应用JNDI技术是Java E ... -
Spring使用Quartz调度器 实现时间点任务(Spring in Action中文版)
2011-03-10 14:08 9987.3.2 使用Quartz调度器 Quartz调度器为调度 ... -
一个分页控件,适合大数据量。可以替换ext的分页控件
2010-11-08 15:44 1116<!doctype html public " ... -
Java的java.nio.Buffer缓冲区基础
2010-10-30 11:02 735缓冲区基础 抽象类Buffer是java.nio包支持缓 ... -
NIO ByteBuffer使用方法
2010-10-30 10:48 1250缓冲区分配和包装 在能够读和写之前,必须有一个缓冲区,用静态方 ... -
What is a Java Thread and How does it work?
2010-10-21 14:27 1018A java thread is an execution c ... -
将标准的java程序封装为Windows下面的服务
2010-10-19 14:02 13271、首先到请下载最新版本的Java Service Wra ... -
HASH表原理
2010-09-19 16:43 875今天由于天气不好 ... -
使用Apache CXF创建Web Service
2009-12-30 09:30 918官方主页:http://cxf.apache.org/ ... -
java.io.File中的绝对路径和相对路径.
2009-11-12 11:26 4991File类是用来构造文件或文件夹的类,在其构造函数中要求传 ... -
JavaScript极速狂飙:大容量字符型数组的快速检索
2009-06-19 20:19 1100JavaScript 在大容量数组 ... -
谈谈JavaScript中的数组、集合及效率
2009-06-19 20:15 1144数组是JavaScript提供的一个内部对象,它是一个标准的集 ... -
log4jxml配置
2009-05-19 14:45 1120<?xml version="1.0 ... -
log4j日志配置
2009-05-19 11:54 932关键字: apache log4j 1、配置根Logg ... -
bat语法的用法
2009-05-15 14:13 1482首先,批处理文件是 ... -
JUnit学习笔记
2009-05-15 10:15 1442这是我在学习的过程中整理记录下来的,其中参考了网上许多文章 ... -
接口和抽象类的区别
2009-04-30 15:15 1413区别一,两者表达的概念不一样。抽象类是一类事物的高 ... -
如何Gwt中使用Session
2008-12-30 13:54 3171在GWT中可以直接使用session信息,只需要用r ...
相关推荐
### 正确理解ThreadLocal:深入解析其工作原理与应用场景 #### 一、ThreadLocal的基本概念 `ThreadLocal`是Java平台提供的一种线程局部变量的解决方案,它为每一个使用该变量的线程都提供了独立的变量副本,使得每...
- 内存泄漏:如果线程长时间存活,或者ThreadLocal对象没有被正确清理,可能导致ThreadLocalMap中的引用无法被垃圾回收,从而造成内存泄漏。 - 不适用于跨线程通信:ThreadLocal只保证同一线程内的数据隔离,不同...
1. 多线程:理解ThreadLocal的使用必须建立在对多线程的理解基础上,包括线程的创建、执行、同步机制等。 2. 并发编程:ThreadLocal是解决并发问题的一种策略,它提供了一种避免共享状态的方式,减少了锁的使用。 3....
ThreadLocal是Java编程中一种非常特殊的变量类型,它主要...正确使用ThreadLocal可以提高代码的并发性能,而滥用则可能导致难以预料的问题。因此,在使用ThreadLocal时,需要充分考虑其生命周期管理和线程安全问题。
at 中专门为每一个 web 应用...理解 `ThreadLocal` 的工作原理以及它如何与类加载器交互,是避免此类问题的关键。在实际开发中,应当养成良好的编程习惯,如使用后及时清理 `ThreadLocal` 变量,以防止内存资源的浪费。
本资料主要聚焦于两种设计模式以及Java中的ThreadLocal特性。 首先,我们来探讨单例模式。单例模式是一种确保一个类只有一个实例,并提供全局访问点的设计模式。在Java中,通常通过私有构造函数、静态工厂方法或...
需要注意的是,尽管ThreadLocal提供了线程局部的变量,但如果不正确地使用,比如在ThreadLocal生命周期结束后没有清理ThreadLocalMap,可能会导致内存泄漏。因此,最佳实践是在不再需要ThreadLocal时调用remove方法...
在实际应用中,理解ThreadLocal在Spring事务处理中的作用有助于优化并发性能和解决多线程环境下的事务问题。例如,如果线程之间需要共享数据,但又不想影响其他线程,ThreadLocal就是一个理想的选择。同时,也要注意...
- **内存泄漏**:如果`ThreadLocal`没有被正确清理,当线程生命周期结束但引用仍然存在时,可能导致内存泄漏。因此,通常在不再需要`ThreadLocal`时,应该调用`remove`方法。 - **性能影响**:过度使用`ThreadLocal`...
其他说明:为了更好地理解ThreadLocal的工作机制,建议实际动手尝试文中提供的实例代码,同时注意不同版本JDK之间的差异可能会导致部分细节有所变化。对于追求高性能并发应用开发的技术人员而言,了解和运用...
让我们通过一个简单的例子来理解`ThreadLocal`的工作机制: ```java public class ThreadLocalExample { private static ThreadLocal<Integer> threadLocal = new ThreadLocal(); public static void main...
ThreadLocal 翻译过来就是本地线程,但是直接这么翻译很难理解 ThreadLocal 的作用。如果换一种说法,可以称为线程本地存储。简单来说,就是 ThreadLocal 为共享变量在每个线程中都创建一个副本,每个线程可以访问...
理解ThreadLocal的工作原理以及如何正确使用它是Java并发编程的关键。 首先,ThreadLocal类的主要作用是为每个线程创建一个单独的变量副本。这意味着在同一个ThreadLocal变量中,不同的线程可以存储各自独立的值,...
Python中的ThreadLocal,全称是`threading.local`,是一个非常重要的并发编程工具。它主要用于在多线程环境中保持线程局部变量,确保每个...正确理解和使用ThreadLocal能够帮助开发者编写出更加健壮和高效的并发程序。
测试用例可以帮助我们更好地理解ThreadLocal的使用和潜在问题: - 创建多个线程,每个线程使用ThreadLocal变量,如果变量引用的是同一个共享对象,修改其中一个线程的变量值,其他线程是否也会看到改变,以此来观察...
ThreadLocal是Java编程语言中的一个类,用于在多线程环境下提供线程局部变量。它为每个线程创建了一个独立的...通过深入理解ThreadLocal的工作原理,可以帮助我们更好地利用这一工具,提高代码的并发性能和可维护性。