ThreadLocal是什么?

ThreadLocal不是Thread

对于多线程资源共享的问题,同步机制采用了以时间换空间的方式,而ThreadLocal采用了以空间换时间的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。

ThreadLocal是解决线程安全问题一个很好的思路,它通过为每个线程提供一个独立的变量副本解决了变量并发访问的冲突问题。在很多情况下,ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。

一般的Web应用划分为展现层、服务层和持久层三个层次,在不同的层中编写对应的逻辑,下层通过接口向上层开放功能调用。在一般情况下,从接收请求到返回响应所经过的所有程序调用都同属于一个线程,同一线程贯通三层这样你就可以根据需要,将一些非线程安全的变量以ThreadLocal存放,在同一次请求响应的调用线程中,所有关联的对象引用到的都是同一个变量。

当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

应用场景:当很多线程需要多次使用同一个对象,并且需要该对象具有相同初始值的时候最适合使用ThreadLocal。

源码

ThreadLocal.set(T value) 方法

 public void set(T value) {
	// 当前线程
	Thread t = Thread.currentThread();
	ThreadLocalMap map = getMap(t);
	if (map != null)
		// ThreadLocalMap 的 key: ThreadLocal 对象 tl
		map.set(this, value);
	else
		createMap(t, value);
}

ThreadLocalMap getMap(Thread t)方法

ThreadLocalMap getMap(Thread t) {
	return t.threadLocals;
}

Thread

ThreadLocal.ThreadLocalMap threadLocals = null;

ThreadLocal map.set(this, value) 方法

 /**
 * Set the value associated with key.
 *
 * @param key the thread local object
 * @param value the value to be set
 */
private void set(ThreadLocal<?> key, Object value) {

	// We don't use a fast path as with get() because it is at
	// least as common to use set() to create new entries as
	// it is to replace existing ones, in which case, a fast
	// path would fail more often than not.

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

ThreadLocal.get()

public T get() {
	
	// 当前线程 
	Thread t = Thread.currentThread();
	
	ThreadLocalMap map = getMap(t);
	
	if (map != null) {
		
		// key: ThreadLocal 对象 tl
		ThreadLocalMap.Entry e = map.getEntry(this);
		
		if (e != null) {
			@SuppressWarnings("unchecked")
			T result = (T)e.value;
			return result;
		}
	}
	return setInitialValue();
}	

关键

由源码可知,ThreadLocal.ThreadLocalMap threadLocals是Thread类的成员变量,底层是数组结构,包装成了 Key-Value结构的Map

set方法

调用ThreadLocal.set(T value)方法进行设置值的时候,是往一个map里面设置值,其中map当前线程的成员变量keyThreadLocal对象,因此每次set的值,都是线程独有的,所以在多个线程间是独立的。

get方法

调用ThreadLocal.get()方法获取值的时候,是从一个map里面获取值,其中map当前线程的成员变量keyThreadLocal对象

使用示例

  • User
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
	private String name;
	private Integer age;
}
  • Holder
public class Holder {
	//使用ThreadLocal来声明UserHolder,这个UserHolder维护了一个变量User,并初始化User
	private static ThreadLocal<User> UserHolder=new ThreadLocal<User>() {  
		public User initialValue() {  
			return new User("Lily",10);  
		}  
	};

	public static User getUser() {
		return UserHolder.get();
	}

	public static void setUser(User user) {
		UserHolder.set(user);;
	}
	
}
  • Thread_1
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Thread_1 extends Thread{
	
	private User user;
 
	public void run(){
		Holder.getUser().setName("Anna");
		Holder.getUser().setAge(20);
		User u=Holder.getUser();
		System.out.println(Thread.currentThread().getName()+"Name:"+u.getName()+"Age:"+u.getAge()); 
	}
}
  • Thread_2
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Thread_2 extends Thread{
	
	private User user;
 
	public void run(){
 
		System.out.println(Thread.currentThread().getName()+"   Name:"+user.getName()+"   Age:"+user.getAge()); 
	}
}
  • 测试:
public class Test {
 
	public static void main(String[] args) {
		
		Thread_1 thread_1 = new Thread_1(Holder.getUser());
		thread_1.setName("线程_1");
	
		Thread_2 thread_2 = new Thread_2(Holder.getUser());
		thread_2.setName("线程_2");
 
		thread_1.start();
		thread_2.start();
	
		System.out.println("User的初始值    Name:"+Holder.getUser().getName()+"   Age:"+Holder.getUser().getAge());
				
	}
}
  • 测试结果(这里有3个线程,因此每次打印的顺序可能不一样)
线程_1       	   Name:Anna   Age:20
线程_2       	   Name:Lily   Age:10
User的初始值        Name:Lily   Age:10
  • 小结

测试结果表明:虽然在线程_1重写的run()方法里面,改变了变量User对象的初始值,但线程_2和main线程中的变量User的属性还是初始值。实际上,这三个线程拿到的都是变量User的副本,每个副本是相互独立的,互不干扰。

ThreadLocalMap源码

static class ThreadLocalMap {

	static class Entry extends WeakReference<ThreadLocal<?>> {
	
		Object value;

		Entry(ThreadLocal<?> k, Object v) {
			
			// k: tl 对象,super(k): 调用父类(WeakReference)的构造方法
			super(k);
			
			value = v;
		}
	}
}

注意

keyey 是弱引用类型的,但 value 并不是弱引用类型的,gc 时弱引用的 key 会被回收,而 value 不会被回收,久而久之,就会导致内存泄漏,因此使用完 ThreadLocal 时,应该调用 remove() 方法清除数据。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值