Java高并发 - 21.线程上下文设计模式

开发过程中,经常会遇到上下文(context),比如structs2的ActionContext、Spring中的ApplicationContext。上下文是贯穿整个系统或阶段生命周期的对象,起哄包含了系统全局的一些信息,比如登录之后的用户信息、账号信息,以及在程序每一个阶段运行的数据。

下面是典型的使用单例对象充当系统级别上下文的例子。

public final class ApplicationContext {
	// 在Context中保存configuration实例
	private ApplicationConfiguration configuration;
	// 在Context中保存runtimeinfo实例
	private RuntimeInfo runtimeInfo;
	// ...其他
	
	// 采用Holder的方式实现单例
	private static class Holder {
		private static ApplicationContext instance = new ApplicationContext();
	}
		
	public static ApplicationContext getContext() {
		return Holder.instance;
	}
		
	public void setConfiguration(ApplicationConfiguration configuration) {
		this.configuration = configuration;
	}
		
	public ApplicationConfiguration getConfiguration() {
		return this.configuration;
	}
	
	public void setRuntimeInfo(RuntionInfo runtimeInfo) {
		this.runtimeInfo = runtimeInfo;
	}
	
	public RuntimeInfo getRuntimeInfo() {
		return this.runtimeInfo;
	}
}

线程上下文设计

有时候,单个线程执行的任务步骤会非常多,后一个步骤的输入可能是前一个步骤的输出,为了使功能单一,我们有时会采用职责链设计模式。

graph LR
A[步骤一] -->|Next| B[步骤二]
A -->|Execute Context context| B
B -->|Next| C[步骤三]
B -->|Execute Context context| C
C -->|Next| D[步骤四]
C -->|Execute Context context| D
D -->|Next| E[步骤五]
D -->|Execute Context context| E

context对象需要从头到尾进行传递,方法参数、调用次数都比较多的时候,这种设计显得比较烦琐。我们可以采用线程的上下文来解决这个问题。

我们在ApplicationContext中增加ActionContext(线程上下文)相关内容:

private ConcurrentHashMap<Thread, ActionContext> contexts = 
		new ConcurrentHashMap<>();

public ActionContext getActionContext() {
	ActionContext actionContext = contexts.get(Thread.currentThread());
	if (actionContext == null) {
		actionContext = new ActionContext();
		contexts.put(Thread.currentThread(), actionContext);
	}
	return actionContext;
}

不同的线程访问getActionContext()方法都会获得不一样的ActionContext实例,这样可以保证线程之间上下文的独立性,同时也不用考虑ActionContext的线程安全性,因此线程上下文又被称为“线程级别的单例”。

通过这种方式定义线程上下文可能会导致内存泄漏。contexts是一个Map的数据结构,用当前线程做key,当线程的生命周期结束后,contexts中的Thread实例不会被释放,与之对应的value也不会被释放,时间长了就会导致内存泄漏。当然这可以通过soft reference或者weak reference等引用类型,让JVM主动尝试回收解决这个问题。

ThreadLocal详解

ThreadLocal为每一个使用该变量的线程都提供了独立的副本,可以做到线程间的数据隔离,每一个线程都可以访问各自内部的副本变量。

在以下场景会使用到ThreadLocal:

  1. 在进行对象跨层传递的时候,可以考虑使用ThreadLocal,避免方法多次传递,打破层次间的约束
  2. 线程间数据隔离,比如线程上下文ActionContext
  3. 进行事务操作,用于存储线程事务信息

ThreadLoacl的使用

public class ThreadLocalExample {
	public static void main(String[] args) {
		// 创建ThreadLocal实例
		ThreadLocal<Integer> tlocal = new ThreadLocal<>();
		// 创建十个线程,使用tlocal
		IntStream.range(0, 10).forEach(i -> new Thread(() -> {
				try {
					// 每个线程都会设置tlocal,但是彼此之间的数据是独立的
					tlocal.set(i);
					System.out.println(currentThread() + " set i " + tlocal.get());
					TimeUnit.SECONDS.sleep(1);
					System.out.println(currentThread() + " get i " + tlocal.get());
				} catch(InterruptedException e) {
					e.printStackTrace();
				}
			}).start()
		);
	}
}

上面代码定义了一个全局唯一的ThreadLocal,然后启动10个线程对ThreadLocal进行set和get操作。通过输出可以发现10个线程之间彼此不会相互影响,每个线程存入ThreadLocal中的i值也是完全不同彼此独立的。

使用ThreadLocal时候,最常用的方法就是initialValue()、set()、get()。

initialValue()方法

initialValue()方法为ThreadLocal要保存的数据类型指定一个初始值,默认返回值为null,示例代码如下:

	// ThreadLocal中initialValue()方法源码
	protected T initialValue() {
		return null;
	}

我们可以通过重写initialValue()方法进行数据初始化。如下面代码所示,线程并未对threadlocal进行set操作,但是还可以通过get方法得到一个初始值,而且每个线程通过get方法获取的值都是不一样的:

	ThreadLocal<Object> threadLocal = new ThreadLocal<Object>() {
		@Override
		protected Object initialValue() {
			return new Object();
		}
	};
	new Thread(() -> {
			System.out.println(threadLocal.get())
	).start();
	System.out.println(threadLocal.get());

使用Java8提供的Supplier函数接口可以简化代码:

	ThreadLocal<Object> threadLocal = ThreadLocal.withInitial(Object::new);

set(T t)方法

set方法主要是为ThreadLocal指定将要存储的数据,如果重写了initialValue()方法,在不调用set(T t)方法的时候,数据的初始值是initialValue()方法的返回值。set方法源码如下:

	// ThreadLocal的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);
	}
	
	// ThreadLocal的createMap方法源码
	void createMap(Thread t, T firstValue) {
		t.threadLocals = new ThreadLocalMap(this, firstValue);
	}
	
	// ThreadLocalMap的set方法源码
	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();
	}

get()方法

get方法返回当前线程在ThreadLocal中的数据备份,当前线程的数据都存放在一个ThreadLocalMap的数据结构中。get方法源码如下:

	// ThreadLocal的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();
	}
	
	// ThreadLocal的setInitialValue方法源码
	private T setInitialValue() {
		T value = initialValue();
		Thread t = Thread.currentThread();
		ThreadLocalMap map = getMap(t);
		if (map != null)
			map.set(this, value);
		else
			createMap(t, value);
		return value;
	}

ThreadLocalMap

ThreadLocalMap是一个类似于HashMap的数据结构,用于存放线程放在ThreadLocal中的数据备份,ThreadLocalMap的所有方法对外部都完全不可见。

ThreadLocalMap中用于存储数据的是Entry,它是一个WeakReference类型的子类。这样设计的原因是为了能够在JVM进行垃圾回收时,能够自动回收,防止内存溢出。

// ThreadLocalMap的Entry源码
static class Entry extends WeakReference<ThreadLocal<?>> {
	/** The Value associated with this ThreadLocal */
	Object value;
	Entry(ThreadLocal<?> k, Object v) {
		super(k);
		value = v;
	}
}

ThreadLocal内存泄露问题

ThreadLocal为解决内存泄露问题做了很多工作:

  1. WeakReference在JVM中触发任意GC(young gc、full gc)时都会导致Entry的回收
  2. 在get数据时增加检查,清楚已经被垃圾回收器回收的Entry

ThreadLocalMap的源码片段如下:

	private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
		Entry[] tab = table;
		int len = tab.length;
		// 查找key为null的Entry
		while (e != null) {
			ThreadLocal<?> k = e.get();
			if (k == key)
				return e;
			if (k == null)
				expungeStaleEntry(i); // 删除key为null的Entry
			else
				i = nextIndex(i, len);
			e = tab[i];
		}
		return null;
	}
	
	private boolean clenaSomeSlots(int i, int n) {
		boolean removed = false;
		Entry[] tab = table;
		int len = tab.length;
		do {
			i = nextIndex(i, len);
			Entry e = tab[i];
			if (e != null && e.get() == null) {
				n = len;
				removed = true;
				i = expungeStaleEntry(i);
			}
		} while ((n >>>= 1) != 0);
	}
	
	// 执行Entry在ThreadLocalMap中的删除操作
	private int enpungeStaleEntry(int staleSlot) {
		Entry[] tab = table;
		int len = tab.length;
		tab[staleSlot].value = null;
		tab[staleSlot] = null;
		size--;
		// Rehash until we encounter null
		Entry e;
		int i;
		for (i = nextIndex(staleSlot, len); (e=tab[i]) != null; i = nextIndex(i, len)) {
			ThreadLocal<?> k = e.get();
			if (k == null) {
				e.value = null;
				tab[i] = null;
				size--;
			} else {
				int h = k.threadLocalHashCode & (len-1);
				if (h != i) {
					tab[i] = null;
					// Unlike Knuth 6.4 Algorithm R, we must scan until null
					// because multiple entries could have been stale.
					while (tab[h] != null)
						h = nextIndex(h, len);
					tab[h] = e;
				}
			}
		}
		return i;
	}

使用ThreadLocal设计线程上下文

public class ActoinContext {
	// 定义ThreadLocal,并且使用Supplier的方式重写initialvalue
	private static final ThreadLocal<Context> context = 
			ThreadLocal.withInitial(Context::new);
			
	public static Context get() {
		return context.get();
	}
	
	// 每一个线程都会有一个独立的Context实例
	static class Context {
		// 在context中的其他成员
		private Configuration configuration;
		private OtherResource otherResource;
		
		public Configuration getConfiguration() {
			return configuration;
		}
		
		public void setConfiguration(Configuration configuration) {
			this.configuration = configuration;
		}
		
		public OtherResource getOtherResource() {
			return otherResource;
		}
		
		public void setOtherResource(OtherResource otherResource) {
			this.otherResource = otherResource;
		}
	}
}