- 浏览: 372859 次
文章分类
最新评论
-
strchi:
这个网站,什么都没有了
做小说搜索网站,这个是不是有可能会侵权的呢? -
从此醉:
楼主倒是给出解决办法啊
Java虚拟机支持的最大内存限制 -
kjmmlzq19851226:
又要增强客户体验,又要降低伪造攻击的概率,╮(╯▽╰)╭,程序 ...
Web安全测试之跨站请求伪造(CSRF)篇(图) -
zhangxinze:
linux下使用Java获取客户端ip地址?大家有何高见,我现 ...
怎样用Java来获取真实的IP地址 -
k_kid9157:
学习 感谢分享:-)
log4j的ConversionPattern参数的格式含义
首先,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 类的代码太多了,我就不帖了,自己去看源码吧。
写了这么多,也不知讲明白了没有,有什么不当的地方还请大家指出来。
发表评论
-
java资源获取分析
2009-11-27 14:41 2334在开发java程序的过程中,我们经常要做的一件事就是获取资源。 ... -
java字符集笔记
2009-05-25 19:05 1170概述 本文主要包括以 ... -
log4j的ConversionPattern参数的格式含义
2009-03-20 15:50 3164Log4j建议只使用四个级别,优先级从高到低分别是ERROR、 ... -
Apache HTTP Server 与 Tomcat 的三种连接方式介绍
2009-03-20 12:00 1244整合 Apache Http Server 和 Tomcat ... -
JavaScript不能做到的6,7事
2009-02-22 11:19 1219虽然在很多方面,JavaScr ... -
TreeMap的使用及注意事项
2008-10-30 20:58 2541TreeMap是红黑树算法 ... -
如何注意HttpSession的线程
2008-09-13 15:12 1409HttpSession session = req ... -
ThreadLocal相关知识2
2008-09-03 14:55 4361ThreadLocal与synchronized Java良好 ... -
JAXP的介绍
2008-08-29 10:37 3823摘要: JAXP (全称Java API for XML P ... -
简单的运用Lucene进行检索
2008-06-17 20:20 1184Lucene不是一个完整的全文索引应用,而是是一个用Java ... -
(转)Java虚拟机参数详解
2008-06-17 11:18 1802http://www.5a520.cn 小说520网 下面的讨 ... -
JAVA面试题(4)
2008-05-31 18:36 1309数据库方面: 1. 存储过 ... -
J2EE初学者需要理解的问题
2008-05-31 18:35 1099一、J2EE提出的背景 1、 ... -
JAVA面试题(3)
2008-05-31 18:32 4993一、Java基础知识1.Java有那些基本数据类型,Strin ... -
java面试题(续)
2008-05-29 21:15 11754. 多线程:在同一应用程序中,有多个顺序流同时执行。同步和异 ... -
java面试题
2008-05-29 21:13 1970应聘Java笔试时可能出现 ...
相关推荐
ThreadLocal 相关知识点 ThreadLocal 是 Java 语言中的一种机制,用于提供线程内部的局部变量。在多线程环境下,ThreadLocal 变量可以保证各个线程的变量相对独立于其他线程内的变量。这种机制可以帮助开发者在多...
以上内容涵盖了从ThreadLocal原理到其在实际开发中的应用,以及相关的多线程、并发编程、HTTP通信等知识点。通过阅读和理解这些资料,开发者可以深化对ThreadLocal的理解,并将其有效地应用于项目中。
**线程局部变量(ThreadLocal)** 在Java编程中,`ThreadLocal`是...以上就是关于`ThreadLocal`及其内部类`ThreadLocalMap`的基础知识,它们在多线程编程中起到关键作用,帮助开发者实现高效、安全的线程局部变量管理。
"ThreadLocal相关知识点总结" ThreadLocal是Java中的一种机制,用于在多线程环境中保存线程上下文信息,并且提供了一种解决多线程程序并发问题的思路。下面是对ThreadLocal的主要知识点的总结: 1. ThreadLocal的...
Quartz 是一个开源的作业调度框架,用于在 Java 应用程序中安排任务。它提供了丰富的 API 和灵活性,使得开发者可以方便地...记得实践是检验真理的唯一标准,动手操作这些 demo,会让你对这些知识点有更深入的理解。
java高并发相关知识,threadLocal,分布式锁,java各种锁等
在"ThreadLocal测试工程"中,我们可以探索以下几个关键知识点: 1. **ThreadLocal类的使用**:ThreadLocal提供了一个`set(T value)`方法用于设置当前线程的ThreadLocal变量值,`get()`方法用于获取当前线程的变量值...
### 知识点一:ThreadLocal的内部结构 每个线程内部都有一个ThreadLocalMap对象,这个对象实际上是一个Map结构,存储了当前线程的ThreadLocal变量以及其对应的值。ThreadLocalMap是ThreadLocal的内部类,它使用...
在Java中,有多种方式可以实现线程间的数据共享和对象独立,其中ThreadLocal是常用的工具之一。 在多线程环境下,共享数据通常会引发线程安全问题,比如上述例子中的“张三给李四转钱”场景,如果两个线程同时操作...
标题“Hibernage_Session_Manager_ThreadLocal”涉及到的是Hibernate框架中的一种优化策略——使用ThreadLocal管理Session。在Java Web开发中,Hibernate是一个非常流行的ORM(对象关系映射)框架,它帮助开发者将...
ThreadLocal 提供了一种线程隔离的变量存储方式,而 Java 中的四种引用类型则帮助我们更好地控制对象的生命周期和内存管理,理解这些概念对于理解和使用 ThreadLocal 至关重要,同时也是面试中经常考察的知识点。
《InheritableThreadLocal & ...总之,理解并熟练运用ThreadLocal和InheritableThreadLocal是Java并发编程中不可或缺的知识点,它们提供了线程安全的局部变量管理机制,能够帮助开发者构建更健壮的多线程应用。
知识点: 1 ThreadLocal 的局限性:ThreadLocal 不能解决跨线程池之间的数据传递问题。 2 InheritableThreadLocal 的局限性:InheritableThreadLocal 仅限于父线程给子线程来传递数据,不能解决跨线程池之间的数据...
知识点2:ThreadLocal数据丢失 ThreadLocal是Java中的一种线程局部存储机制,用于在线程中传递数据。但是,在Hystrix线程隔离模式下,ThreadLocal数据可能会丢失,因为Hystrix将请求放入Hystrix的线程池中去执行,...
以下是对标题和描述中所述知识点的详细说明: 1. **与 Synchronized 的区别** - `synchronized` 关键字是用于控制对共享资源的并发访问,它确保同一时刻只有一个线程可以执行特定代码块,从而实现线程同步。而 `...
这个Entry数组的键是ThreadLocal对象本身(弱引用),而值是线程相关的对象。这样设计的原因是,一个线程可能有多个ThreadLocal实例,每个实例对应不同的变量副本。 ThreadLocal的`set`方法是将值与当前线程关联的...
"ThreadLocal知识点详解" ThreadLocal是一个本地线程副本变量工具类,主要用于将私有线程和该线程存放的副本对象做一个映射,各个线程之间的变量互不干扰,在高并发场景下,可以实现无状态的调用,特别适用于各个...
### 知识点详解:Java.lang.ThreadLocal 类 #### 一、概述 **ThreadLocal** 并非线程的一种特殊实现形式,而是一种为每个线程提供独立副本的机制,通常被称为“线程局部变量”。这种机制使得每个线程都可以独立...
总结一下,ThreadLocal的主要知识点包括: 1. **线程隔离**:每个线程拥有ThreadLocal变量的独立副本,互不影响。 2. **共享对象,独立值**:所有线程共享同一个ThreadLocal对象,但访问时看到的是各自的副本。 3. ...