java的ThreadLocal

早在Java 1.2推出之时,Java平台中就引入了一个新的支持:java.lang.ThreadLocal,给我们在编写多线程程序时提供了一种新的选择。使用这个工具类可以很简洁地编写出优美的多线程程序。

     ThreadLocal是什么 ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是thread local variable(线程局部变量)。也许把它命名为ThreadLocalVar更加合适。线程局部变量(ThreadLocal)其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有该变量。线程局部变量并不是Java的新发明,在其它的一些语言编译器实现(如IBM XL FORTRAN)中,它在语言的层次提供了直接的支持。因为Java中没有提供在语言层次的直接支持,而是提供了一个ThreadLocal的类来提供支持,所以,在Java中编写线程局部变量的代码相对比较笨拙,这也许是线程局部变量没有在Java中得到很好的普及的一个原因吧。

    TheadLocal包含了一组get(),set(Object)方法,可以获得当前线程的放进去的对象。
    ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。

    另外,说ThreadLocal使得各线程能够保持各自独立的一个对象,这个对象的创建并不是通过ThreadLocal.set()来实现的,set()并不会做什么对象的拷贝,而是每个线程之前已经创建好的对象。通 过ThreadLocal.set()将这个新创建的对象的引用以当前线程为key,保存TheadLocal的一个map中,执行 ThreadLocal.get()时,各线程从map中取出以当前线程为key的对象,因此取出来的是各自自己线程中的对象

下面来看看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 {   
   
     ........   
   
     } 


 


以hibernate中典型的ThreadLocal的应用:
代码
private static final ThreadLocal threadSession = new ThreadLocal();   
   
public static Session getSession() throws InfrastructureException {   
     Session s = (Session) threadSession.get();   
    try {   
        if (s == null) { 

          //每一个线程第一次使用getSession都会到这,调用openSession。

             s = getSessionFactory().openSession();   
             threadSession.set(s);   
         }   
     } catch (HibernateException ex) {   
        throw new InfrastructureException(ex);   
     }   
    return s;   
} 


 


你可能感兴趣的:(java,thread,多线程,session,Class,fortran)