Java并发编程 | 第七篇:ThreadLocal

ThreadLocal介绍

ThreadLocal为每个使用变量的线程提供独立的变量副本,所以每一个线程可以独立修改自己的副本,从而隔离了多个线程对数据的访问冲突。
ThreadLocal 适用于每个线程需要自己独立的实例且该实例需要在多个方法中被使用,也即变量在线程间隔离而在方法或类间共享的场景。

注意:跟多线程并发问题没关系,跟多线程并发问题没关系,跟多线程并发问题没关系

ThreadLocal 适用于如下两种场景

  • 每个线程需要有自己单独的实例
  • 实例需要在多个方法中共享,但不希望被多线程共享

ThreadLocal和run方法的局部变量什么区别

  • ThreadLocal可以跨方法共享变量
  • run局部变量只能在单个方法

ThreadLocal简单实现

public class TestNum {
	// 通过匿名内部类的initialValue()方法,指定初始化值
	private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {

		public Integer initialValue() {
			return 0;
		}
	};

	//获得下一个序列值
	public int getNextNum() {
		seqNum.set(seqNum.get() - 1);
		return seqNum.get();
	}
    //ThreadLocal为每一个线程提供了单独的副本
	public static void main(String[] args) {
       TestNum sn=new TestNum();
       
       TestClient t1=new TestClient(sn);
       TestClient t2=new TestClient(sn);
       TestClient t3=new TestClient(sn);
       
       t1.start();
       t2.start();
       t3.start();
	}
	
	private static class TestClient extends Thread{
		private TestNum sn;
		
		public TestClient(TestNum sn){
			this.sn=sn;
		}
		
		
		@Override
		public void run() {
			for(int i=0;i<3;i++){
				//每个线程打出3个序列值
				System.out.println("thread["+Thread.currentThread().getName()
						+"]-->sn["+sn.getNextNum()+"]");
			}
		}
	}
}

我们发现每个TestClient线程产生的序号虽然都共享同一TestNum实例,但它们并没有发现相互干扰,因为ThreadLocal为每一个线程提供了单独的副本。

ThreadLocal的实现原理

我们需要关注ThreadLocal的set()方法和get()方法
下面的set()源码

   public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

可以看出,先获取当前线程对象,然后通过getMap()拿到线程的ThreadLocalMap,并将值设置进去,ThreadLocalMap的key就当前对象,value就我们要的值。线程隔离原理就在这个ThreadLocalMap,ThreadLocalMap是ThreadLocal类的一个静态内部类,每个线程都有独立的ThreadLocalMap副本,里面存储的值只能对当前线程读取和修改。ThreadLocal类通过操作每一个线程特有的ThreadLocalMap副本,从而实现了变量访问不同线程的隔离

在看get()方法

 public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

先取当前线程的ThreadLocalMap对象,通过将自己作为key获取内部数据

了解源码后,你会发现这些变量是维护在Thread类内部的,也就ThreadLocalMap,这也就说只要外部的Thread线程不退出,对象的引用将一直存在
再看Thread类的exit()方法,里面包括清除ThreadLocalMap

  private void exit() {
        if (group != null) {
            group.threadTerminated(this);
            group = null;
        }
        /* Aggressively null out all reference fields: see bug 4006245 */
        target = null;
        /* Speed the release of some of these resources */
        threadLocals = null;
        inheritableThreadLocals = null;
        inheritedAccessControlContext = null;
        blocker = null;
        uncaughtExceptionHandler = null;
    }

如果我们使用线程池,当前线程很可能总是存在,那么也会导致对象一直保存ThreadLocalMap,为了避免内存泄漏,我们需要使用ThrealLocal.remove()将变量移除。我们有时候可以为加速垃圾回收,会特意写obj=null类似的代码,obj指向的对象会更容易被垃圾回收器发现,然后加速回收

ThreadLocal对性能帮助

工作线程的内部逻辑有两种模式:
1、多线程共享一个Random(mode=0)
2、多线程各分配一个Random(mode=1)

package ThreadLocal;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class tRnd {
	// 每个线程产生的随机数的数量
	public static final int GEN_COUNT = 10000000;
	// 参与工作的线程数量
	public static final int THREAD_COUNT = 4;
	static ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
	// 被多线程共享的Random实例,用于产生随机数
	public static Random rnd = new Random(123);

	public static ThreadLocal<Random> tRnd = new ThreadLocal<Random>() {
		@Override
		protected Random initialValue() {
			// TODO Auto-generated method stub
			return new Random(123);
		}

	};

	public static class RndTask implements Callable<Long> {
		private int mode = 0;

		public RndTask(int mode) {
			this.mode = mode;
		}

		public Random getRandom() {
			if (mode == 0) {
				return rnd;
			} else if (mode == 1) {
				return tRnd.get();
			} else {
				return null;
			}
		}

		@Override
		public Long call() throws Exception {
			// TODO Auto-generated method stub
			long b=System.currentTimeMillis();
			for(int i=0;i<GEN_COUNT;i++){
				getRandom().nextInt();
			}
			long e=System.currentTimeMillis();
			System.out.println(Thread.currentThread().getName()+" spend "+(e-b)+"ms");
			
			return e-b;
		}
		

	}
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//Future表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。
		Future<Long>[] futs=new Future[THREAD_COUNT];
		for(int i=0;i<THREAD_COUNT;i++){
			futs[i]=es.submit(new RndTask(0));
		}
		long totaltime=0;
		for(int i=0;i<THREAD_COUNT;i++){
			totaltime+=futs[i].get();
		}
		System.out.println("多线程访问同一Random实例:"+totaltime+"ms");
		
		for(int i=0;i<THREAD_COUNT;i++){
			futs[i]=es.submit(new RndTask(1));
		}
		 totaltime=0;
		for(int i=0;i<THREAD_COUNT;i++){
			totaltime+=futs[i].get();
		}
		System.out.println("使用ThreadLocal包装Random实例:"+totaltime+"ms");
		
		es.shutdown();
	}

}

这里写图片描述

防止内存泄漏

Entry虽然是弱引用,但它是 ThreadLocal 类型的弱引用(也即上文所述它是对 键 的弱引用),而非具体实例的的弱引用,所以无法避免具体实例相关的内存泄漏。
对于已经不再被使用且已被回收的 ThreadLocal 对象,它在每个线程内对应的实例由于被线程的 ThreadLocalMap 的 Entry 强引用,无法被回收,可能会造成内存泄漏。
针对该问题,ThreadLocalMap 的 set 方法中,通过 replaceStaleEntry 方法将所有键为 null 的 Entry 的值设置为 null,从而使得该值可被回收。另外,会在 rehash 方法中通过 expungeStaleEntry 方法将键和值为 null 的 Entry 设置为 null 从而使得该 Entry 可被回收。通过这种方式,ThreadLocal 可防止内存泄漏。

private void set(ThreadLocal<?> key, Object value) {
  Entry[] tab = table;
  int len = tab.length;
  int i = key.threadLocalHashCode & (len-1);
  for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {
    ThreadLocal<?> k = e.get();
    if (k == key) {
      e.value = value;
      return;
    }
    if (k == null) {
      replaceStaleEntry(key, value, i);
      return;
    }
  }
  tab[i] = new Entry(key, value);
  int sz = ++size;
  if (!cleanSomeSlots(i, sz) && sz >= threshold)
    rehash();
}

参考:《Java高并发程序设计》
http://blog.csdn.net/lufeng20/article/details/24314381

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值