ITeye博客

Java ThreadLocal

labreeze · 2014-11-23 22:09 · JAVA基础 · 编程语言 · Markdown

ThreadLocal其实是个很常见的对象,可是你知道它的原理么?为何会设计ThreadLocal?

  参考了以下博客

         http://my.oschina.net/clopopo/blog/149368

         java特种兵

 

1.设计背景 下面一段网上摘录

   ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了线程保持对象的方法和避免参数传递的方便的对象访问方式 

   ThreadLocal的应用场合,最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。

   官方解释

   该类提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物,因为访问某个变量(通过其 get 或 set 方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本。ThreadLocal 实例通常是类中的 private static 字段,它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。 

 

2.ThreadLocal原理

    疑问一:ThreadLocal里面的map的键值是当前线程,这样如果有两个变量ThreadLocal<String> t1,ThreadLocal<String> t2 那么他们set的时候会冲掉之前的变量后来跟进代码发现原来不是这样的。 

   case如下

    

public class TestThreadLocal {
	
	public static ThreadLocal<String> resource1 = new ThreadLocal<String>();
	public static ThreadLocal<String> resource2 = new ThreadLocal<String>();
	
	public static void main(String[] args) {
		
		for(int i = 0; i< 10 ;i++){
			final int index = i;
			new Thread(new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					resource1.set(index+"----");
					resource2.set(index +"...");
					System.out.println(resource1.get()+"||||||"+resource2.get());
					resource1.remove();
					resource2.remove();
				}
			}).start();
		}
	}
	
}

     结果如下

     

0----||||||0...
3----||||||3...
2----||||||2...
1----||||||1...
4----||||||4...
5----||||||5...
7----||||||7...
6----||||||6...
8----||||||8...
9----||||||9...

     发现他们之间根本就是互不影响的,跟进ThreadLocal源码发现了错误在哪里了。

    

 /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to 
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's 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);
    }

    

  可以发现这里的map确实是线程里面的。 

    结论:键值是this,这里的this应该是调用该方法的对象啊,所以是resource1或者ressource2

 

 

     疑问二,如果ThreadLocal存储的是对象呢,每个线程是一份拷贝呢,还是都是相同的对象呢?

     case

    

public class TestThreadLocal2 {
	public static ThreadLocal<Student> resource = new ThreadLocal<Student>();
	static class Student{
		String name ;
		
		public Student(String name){
			this.name = name;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final Student st = new Student("1111111");
		
		for(int i = 0; i< 10 ;i++){
			final int index = i;
			Thread.sleep(100);
			new Thread(new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					if(index %2 == 0){
						st.setName("1111"+index);
					}
					resource.set(st);
					System.out.println(st.hashCode()+","+resource.get().hashCode()+","+resource.get().getName());
					resource.remove();
				}
			}).start();
		}
	}

}

     输出结果如下:

     可以发现每个线程取出来的都是同一个hashCode,说明大家使用的是同一个对象,实际内存则存在堆中,如果这样使用的话应该还是存在可见性的问题。

    

1069480624,1069480624,11110
1069480624,1069480624,11110
1069480624,1069480624,11112
1069480624,1069480624,11112
1069480624,1069480624,11114
1069480624,1069480624,11114
1069480624,1069480624,11116
1069480624,1069480624,11116
1069480624,1069480624,11118
1069480624,1069480624,11118

 

     疑问三,比如某些场景如connection我想让每个线程使用自己的connection对象,不能让他们之间相互影响ThreadLocal就没有办法了吗? 当然是有的

    case 

    

public class TestThreadLocal2 {
	public static ThreadLocal<Student> resource = new ThreadLocal<Student>(){
		 protected Student initialValue() {
			 return new Student("111111111");
		 };
	};
	static class Student{
		String name ;
		
		public Student(String name){
			this.name = name;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final Student st = new Student("1111111");
		
		for(int i = 0; i< 10 ;i++){
			final int index = i;
			Thread.sleep(100);
			new Thread(new Runnable() {
				//这里没有set直接get了
				public void run() {
					System.out.println(st.hashCode()+","+resource.get().hashCode()+","+resource.get().getName());
					resource.remove();
				}
			}).start();
		}
	}

}

     结果如下

322722178,1595436971,111111111
322722178,616699029,111111111
322722178,482535999,111111111
322722178,16993205,111111111
322722178,1286693589,111111111
322722178,1535562945,111111111
322722178,729943514,111111111
322722178,646414701,111111111
322722178,2131949076,111111111
322722178,1018730552,111111111

      发现get出来的每个对象的hashCode都不相同。为何没有set直接get会有这种效果呢?

    

/**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} 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) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。