ThreadLocal essays

ThreadLocal <T> for storing thread cache, the cache operation of the threads achieved by a simple operation, so that the isolation buffer

Source posted below:

//如图第①步 像线程中存入123 至于数据结构怎么存 下面解释
public class App { public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(); public static void main( String[] args ) { threadLocal.set(123); threadLocal.get(); } } public void set(T value) { //获取当前线程 Thread t = Thread.currentThread(); //如图第②步 第③步 获取当前线程t中的threadLocals ThreadLocalMap map = getMap(t); if (map != null) //如图第④步 向map中put键值对,键为当前threadLocal对象,值为value, //至于map如何操作可近似理解为 HashMap的put操作 不是本文重点不多讲 map.set(this, value); else //如果当前线程threadLocals为空 则创建并以此键值对初始化 createMap(t, value); } //获取线程中的threadLocals ThreadLocalMap getMap(Thread t) { return t.threadLocals; } //创建并初始化threadLocals void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }

Description of the above code is in the stored Thread there threadLocals <ThreadLocal, value> value pairs for which the basic principle understand the general;

Here's the thread cache values ​​Codes

Value posted the code:

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) { //类似HashMap取值,键为当前threadLocal对象 ThreadLocalMap.Entry e = map.getEntry(this); //如果不为空则做Object的转换 if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } //如果map为空则以 键值对<this,null>初始化 Thread t中属性threadLocals return setInitialValue(); } //这段代码就是set的翻版 只不过value的值为null 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; }

Summary: ThreadLocal objects are typically shared object as global for each thread, the object is to have this key,

Guess you like

Origin www.cnblogs.com/xieyanke/p/12143421.html