关于ThreadLocal

防止任务在共享资源上产生冲突的方式除了同步,还有一种就是根除对变量的共享。线程本地存储(ThreadLocal)是一种自动化机制,可以为使用相同变量的每个不同的线程都创建不同的存储,通过把数据放在ThreadLocal中就可以让每个线程创建一个该变量的副本,从而避免并发访问的线程安全问题。早在JDK 1.2退出之时,Java就为多线程编程提供了一个ThreadLocal类;从Java 5.0 以后,Java引入了泛型支持,Java为该ThreadLocal类增加了泛型支持,即ThreadLocal<T>。

ThreadLocal类除构造器之外,只有三个public方法,分别是:

public T get(); 返回此线程局部变量的当前线程副本中的值。

public void set(T value); 将此线程局部变量的当前线程副本中的值设置为指定值。

public void remove(); 移除此线程局部变量当前线程的值。

下面是一个ThreadLocal类解决变量共享冲突的示例:

package thread.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Account {
	private ThreadLocal<String> name=new ThreadLocal<>();
	
	public Account(String name) {
		this.name.set(name);
	}
	public String getName() {
		return name.get();
	}

	public void setName(String name) {
		this.name.set(name);
	}
}
class MyThread implements Runnable {
	Account account;
	public MyThread(Account account) {
		this.account=account;
	}
	@Override
	public void run() {
		for(int i=0;i<10;i++) {
			if(i==6) {
				account.setName(Thread.currentThread().getName());
			}
			System.out.println(account.getName()+" name of i: "+i);
		}
	}
	
}
public class ThreadLocalTest {

	/**       
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService ex=Executors.newCachedThreadPool();
		Account accountA=new Account("A");
		Account accountB=new Account("B");
		ex.execute(new MyThread(accountA));
		ex.execute(new MyThread(accountB));
		ex.shutdown();
	}

}/* Output:
null name of i: 0
null name of i: 1
null name of i: 0
null name of i: 2
null name of i: 1
null name of i: 3
null name of i: 2
null name of i: 3
null name of i: 4
null name of i: 5
pool-1-thread-2 name of i: 6
pool-1-thread-2 name of i: 7
pool-1-thread-2 name of i: 8
pool-1-thread-2 name of i: 9
null name of i: 4
null name of i: 5
pool-1-thread-1 name of i: 6
pool-1-thread-1 name of i: 7
pool-1-thread-1 name of i: 8
pool-1-thread-1 name of i: 9
*///:~

ThreadLocal 将需要并发访问的资源复制多份,每个线程拥有一份资源,每个线程都拥有自己的资源副本,从而也就没有必要对变量进行同步了。ThreadLocal并不能代替同步机制,两者面向的领域不同。同步机制是为了同步多个线程对相同资源的并发访问,是多个线程之间进行通信的有效方式;而ThreadLocal是为了隔离多个线程的数据共享,从根本上避免多个线程之间对共享资源的竞争。通常,如果多个线程之间需要共享资源,以达到线程之间的通信功能,就使用同步机制;如果仅仅是需要隔离多个线程之间的共享冲突,则可以使用ThreadLocal。

那么,ThreadLocal又是如何实现为每个线程产生一份资源副本的呢?

首先来看一下ThreadLocal三个public方法的源代码:

    /**
     * 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();
    }


    /**
     * 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);
    }


    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * <tt>initialValue</tt> method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

简单解释一下上面的代码,首先说一下每个方法都有涉及的ThreadLocalMap getMap(Thread t);方法,其实代码很简单:

    /**
     * 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;
    }

可以看出对于每个访问ThreadLocal对象的线程,都有一个ThreadLocalMap 类型的threadLocals 实例Field,查看Thread的源码也可以发现这一点:

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

而ThreadLocalMap则是ThreadLocal的一个静态内部类,具体代码不再贴出,参考JDK源码即可。ThreadLocalMap主要提供一个静态内部类Entry,一个Entry类型的数组table,用于存放ThreadLocal以及ThreadLocal存储的变量,这也是对于每个线程,都有ThreadLocal变量的一个副本的关键所在。

对于public T get();方法,如果当前线程已经存储此ThreadLocal所持有的变量的副本,即当前线程的threadLocals实例变量不为空,则直接返回threadLocals中存储的当前ThreadLocal对应的变量的值;否则,初始化当前线程的threadLocals实例Field,将当前ThreadLocal对应的变量设为null,并返回null。

对于public void set(T value);方法,如果当前线程已经存储此ThreadLocal所持有的变量的副本,即当前线程的threadLocals实例变量不为空,则将当前ThreadLocal对应的变量值更新为value;否则,初始化当前线程的threadLocals实例Field,将当前ThreadLocal对应的变量设为value。

对于public void remove();方法,如果当前线程已经存储此ThreadLocal所持有的变量的副本,即当前线程的threadLocals实例变量不为空,则将当前ThreadLocal及对应的变量值删除。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值