关于ThreadLocal

一、概述
ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是 threadlocalvariable(线程局部变量)。也许把它命名为ThreadLocalVar更加合适。线程局部变量 (ThreadLocal)其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是Java中一种较为特殊的线程绑定机制,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。

从线程的角度看,每个线程都保持一个对其线程局部变量副本的隐式引用,只要线程是活动的并且 ThreadLocal 实例是可访问的;在线程消失之后,其线程局部实例的所有副本都会被垃圾回收(除非存在对这些副本的其他引用)。
通过ThreadLocal存取的数据,总是与当前线程相关,也就是说,JVM 为每个运行的线程,绑定了私有的本地实例存取空间,从而为多线程环境常出现的并发访问问题提供了一种隔离机制。
ThreadLocal是如何做到为每一个线程维护变量的副本的呢?其实实现的思路很简单,在ThreadLocal类中有一个Map,用于存储每一个线程的变量的副本。
概括起来说,对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。

二、API说明

ThreadLocal()
          创建一个线程本地变量。
T get()
         返回此线程局部变量的当前线程副本中的值,如果这是线程第一次调用该方法,则创建并初始化此副本。
protected  T initialValue()
          返回此线程局部变量的当前线程的初始值。最多在每次访问线程来获得每个线程局部变量时调用此方法一次,即线程第一次使用 get() 方法访问变量的时候。如果线程先于 get 方法调用 set(T) 方法,则不会在线程中再调用 initialValue 方法。
   若该实现只返回 null;如果程序员希望将线程局部变量初始化为 null 以外的某个值,则必须为 ThreadLocal 创建子类,并重写此方法。通常,将使用匿名内部类。initialValue 的典型实现将调用一个适当的构造方法,并返回新构造的对象。
void remove()
          移除此线程局部变量的值。这可能有助于减少线程局部变量的存储需求。如果再次访问此线程局部变量,那么在默认情况下它将拥有其 initialValue。
void set(T value)
          将此线程局部变量的当前线程副本中的值设置为指定值。许多应用程序不需要这项功能,它们只依赖于 initialValue() 方法来设置线程局部变量的值。
在程序中一般都重写initialValue方法,以给定一个特定的初始值。
三、典型实例
1、Hiberante的Session 工具类HibernateUtil
这个类是Hibernate官方文档中HibernateUtil类,用于session管理。

Java代码 复制代码
  1. public class HibernateUtil {   
  2.     private static Log log = LogFactory.getLog(HibernateUtil.class);   
  3.     private static final SessionFactory sessionFactory;     //定义SessionFactory   
  4.   
  5.     static {   
  6.         try {   
  7.             // 通过默认配置文件hibernate.cfg.xml创建SessionFactory   
  8.             sessionFactory = new Configuration().configure().buildSessionFactory();   
  9.         } catch (Throwable ex) {   
  10.             log.error("初始化SessionFactory失败!", ex);   
  11.             throw new ExceptionInInitializerError(ex);   
  12.         }   
  13.     }   
  14.   
  15.     //创建线程局部变量session,用来保存Hibernate的Session   
  16.     public static final ThreadLocal session = new ThreadLocal();   
  17.   
  18.      
  19.     public static Session currentSession() throws HibernateException {   
  20.         Session s = (Session) session.get();   
  21.         // 如果Session还没有打开,则新开一个Session   
  22.         if (s == null) {   
  23.             s = sessionFactory.openSession();   
  24.             session.set(s);         //将新开的Session保存到线程局部变量中   
  25.         }   
  26.         return s;   
  27.     }   
  28.   
  29.     public static void closeSession() throws HibernateException {   
  30.         //获取线程局部变量,并强制转换为Session类型   
  31.         Session s = (Session) session.get();   
  32.         session.set(null);   
  33.         if (s != null)   
  34.             s.close();   
  35.     }   
  36. }  
public class HibernateUtil {
    private static Log log = LogFactory.getLog(HibernateUtil.class);
    private static final SessionFactory sessionFactory;     //定义SessionFactory

    static {
        try {
            // 通过默认配置文件hibernate.cfg.xml创建SessionFactory
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            log.error("初始化SessionFactory失败!", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    //创建线程局部变量session,用来保存Hibernate的Session
    public static final ThreadLocal session = new ThreadLocal();

  
    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // 如果Session还没有打开,则新开一个Session
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);         //将新开的Session保存到线程局部变量中
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        //获取线程局部变量,并强制转换为Session类型
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
}



在这个类中,由于没有重写ThreadLocal的initialValue()方法,则首次创建线程局部变量session其初始值为 null,第一次调用currentSession()的时候,线程局部变量的get()方法也为null。因此,对session做了判断,如果为 null,则新开一个Session,并保存到线程局部变量session中,这一步非常的关键,这也是“public static final ThreadLocal session = new ThreadLocal()”所创建对象session能强制转换为Hibernate Session对象的原因。
2、另外一个实例
创建一个Bean,通过不同的线程对象设置Bean属性,保证各个线程Bean对象的独立性。


Java代码 复制代码
  1. public class Student {   
  2.     private int age = 0;   //年龄   
  3.   
  4.     public int getAge() {   
  5.         return this.age;   
  6.     }   
  7.   
  8.     public void setAge(int age) {   
  9.         this.age = age;   
  10.     }   
  11. }   
  12.   
  13.   
  14. public class ThreadLocalDemo implements Runnable {   
  15.     //创建线程局部变量studentLocal,在后面你会发现用来保存Student对象   
  16.     private final static ThreadLocal studentLocal = new ThreadLocal();   
  17.   
  18.     public static void main(String[] agrs) {   
  19.         ThreadLocalDemo td = new ThreadLocalDemo();   
  20.         Thread t1 = new Thread(td, "a");   
  21.         Thread t2 = new Thread(td, "b");   
  22.         t1.start();   
  23.         t2.start();   
  24.     }   
  25.   
  26.     public void run() {   
  27.         accessStudent();   
  28.     }   
  29.   
  30.      
  31.     public void accessStudent() {   
  32.         //获取当前线程的名字   
  33.         String currentThreadName = Thread.currentThread().getName();   
  34.         System.out.println(currentThreadName + " is running!");   
  35.         //产生一个随机数并打印   
  36.         Random random = new Random();   
  37.         int age = random.nextInt(100);   
  38.         System.out.println("thread " + currentThreadName + " set age to:" + age);   
  39.         //获取一个Student对象,并将随机数年龄插入到对象属性中   
  40.         Student student = getStudent();   
  41.         student.setAge(age);   
  42.         System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge());   
  43.         try {   
  44.             Thread.sleep(500);   
  45.         }   
  46.         catch (InterruptedException ex) {   
  47.             ex.printStackTrace();   
  48.         }   
  49.         System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge());   
  50.     }   
  51.   
  52.     protected Student getStudent() {   
  53.         //获取本地线程变量并强制转换为Student类型   
  54.         Student student = (Student) studentLocal.get();   
  55.         //线程首次执行此方法的时候,studentLocal.get()肯定为null   
  56.         if (student == null) {   
  57.             //创建一个Student对象,并保存到本地线程变量studentLocal中   
  58.             student = new Student();   
  59.             studentLocal.set(student);   
  60.         }   
  61.         return student;   
  62.     }   
  63. }   
  64.   
  65. 运行结果:   
  66. a is running!   
  67. thread a set age to:76  
  68. b is running!   
  69. thread b set age to:27  
  70. thread a first read age is:76  
  71. thread b first read age is:27  
  72. thread a second read age is:76  
  73. thread b second read age is:27  
public class Student {
    private int age = 0;   //年龄

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


public class ThreadLocalDemo implements Runnable {
    //创建线程局部变量studentLocal,在后面你会发现用来保存Student对象
    private final static ThreadLocal studentLocal = new ThreadLocal();

    public static void main(String[] agrs) {
        ThreadLocalDemo td = new ThreadLocalDemo();
        Thread t1 = new Thread(td, "a");
        Thread t2 = new Thread(td, "b");
        t1.start();
        t2.start();
    }

    public void run() {
        accessStudent();
    }

  
    public void accessStudent() {
        //获取当前线程的名字
        String currentThreadName = Thread.currentThread().getName();
        System.out.println(currentThreadName + " is running!");
        //产生一个随机数并打印
        Random random = new Random();
        int age = random.nextInt(100);
        System.out.println("thread " + currentThreadName + " set age to:" + age);
        //获取一个Student对象,并将随机数年龄插入到对象属性中
        Student student = getStudent();
        student.setAge(age);
        System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge());
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge());
    }

    protected Student getStudent() {
        //获取本地线程变量并强制转换为Student类型
        Student student = (Student) studentLocal.get();
        //线程首次执行此方法的时候,studentLocal.get()肯定为null
        if (student == null) {
            //创建一个Student对象,并保存到本地线程变量studentLocal中
            student = new Student();
            studentLocal.set(student);
        }
        return student;
    }
}

运行结果:
a is running!
thread a set age to:76
b is running!
thread b set age to:27
thread a first read age is:76
thread b first read age is:27
thread a second read age is:76
thread b second read age is:27


可以看到a、b两个线程age在不同时刻打印的值是完全相同的。这个程序通过妙用ThreadLocal,既实现多线程并发,游兼顾数据的安全性。
四、总结
ThreadLocal使用场合主要解决多线程中数据数据因并发产生不一致问题。ThreadLocal为每个线程的中并发访问的数据提供一个副本,通过访问副本来运行业务,这样的结果是耗费了内存,单大大减少了线程同步所带来性能消耗,也减少了线程并发控制的复杂度。
ThreadLocal不能使用原子类型,只能使用Object类型。ThreadLocal的使用比synchronized要简单得多。
ThreadLocal和Synchonized都用于解决多线程并发访问。但是ThreadLocal与synchronized有本质的区别。synchronized是利用锁的机制,使变量或代码块在某一时该只能被一个线程访问。而ThreadLocal为每一个线程都提供了变量的副本,使得每个线程在某一时间访问到的并不是同一个对象,这样就隔离了多个线程对数据的数据共享。而Synchronized却正好相反,它用于在多个线程间通信时能够获得数据共享。
Synchronized用于线程间的数据共享,而ThreadLocal则用于线程间的数据隔离。
当然ThreadLocal并不能替代synchronized,它们处理不同的问题域。Synchronized用于实现同步机制,比ThreadLocal更加复杂。
五、ThreadLocal使用的一般步骤

1、在多线程的类(如ThreadDemo类)中,创建一个ThreadLocal对象threadXxx,用来保存线程间需要隔离处理的对象xxx。
2、在ThreadDemo类中,创建一个获取要隔离访问的数据的方法getXxx(),在方法中判断,若ThreadLocal对象为null时候,应该new()一个隔离访问类型的对象,并强制转换为要应用的类型。
3、在ThreadDemo类的run()方法中,通过getXxx()方法获取要操作的数据,这样可以保证每个线程对应一个数据对象,在任何时刻都操作的是这个对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值