Thread
private ClassLoader contextClassLoader; 类加载器 之前有写不讲。。
private AccessControlContext inheritedAccessControlContext; // 权限控制类..
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal线程缓存
public void set(T value) public void get() threadlocal.get() 方法的时候,首先会根据这个线程得到这个线程的 threadLocals 属性
static class ThreadLocalMap // ThreadLocal的静态内部类 hashmap key 是ThreadLocal value 是T
static class Entry extends WeakReference// ThreadLocalMap 的静态内部类 继承弱引用
WeakReference的一个特点是它何时被回收是不可确定的, 因为这是由GC运行的不确定性所确定的. 所以, 一般用weak reference引用的对象是有价值被cache, 而且很容易被重新被构建, 且很消耗内存的对象.
ReferenceQueue
在weak reference指向的对象被回收后, weak reference本身其实也就没有用了. java提供了一个ReferenceQueue来保存这些所指向的对象已经被回收的reference. 用法是在定义WeakReference的时候将一个ReferenceQueue的对象作为参数传入构造函数.
SoftReference
soft reference和weak reference一样, 但被GC回收的时候需要多一个条件: 当系统内存不足时(GC是如何判定系统内存不足? 是否有参数可以配置这个threshold?), soft reference指向的object才会被回收. 正因为有这个特性, soft reference比weak reference更加适合做cache objects的reference. 因为它可以尽可能的retain cached objects, 减少重建他们所需的时间和消耗.
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
* This class extends ThreadLocal to provide inheritance of values* from parent thread to child thread: when a child thread is created, the* child receives initial values for all inheritable thread-local variables* for which the parent has values. Normally the child's values will be* identical to the parent's; however, the child's value can be made an* arbitrary function of the parent's by overriding the childValue* method in this class.**Inheritable thread-local variables are used in preference to* ordinary thread-local variables when the per-thread-attribute being* maintained in the variable (e.g., User ID, Transaction ID) must be* automatically transmitted to any child threads that are created.
就是说这个类继承了ThreadLocal 然后父线程在去创建子线程的时候 子线程将会继承所有的thread-local variables 。
那么如何实现的呢
实例化 thread 的时候 在thread的构造方法里
if (parent.inheritableThreadLocals != null) this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) { return new ThreadLocalMap(parentMap);}
private ThreadLocalMap(ThreadLocalMap parentMap) { Entry[] parentTable = parentMap.table; int len = parentTable.length; setThreshold(len); table = new Entry[len]; for (int j = 0; j < len; j++) { Entry e = parentTable[j]; if (e != null) { ThreadLocal key = e.get(); if (key != null) { Object value = key.childValue(e.value); Entry c = new Entry(key, value); int h = key.threadLocalHashCode & (len - 1); while (table[h] != null) h = nextIndex(h, len); table[h] = c; size++; } } }}
------------------------------------------------
CountDownLatch:主线程阻塞 ,其余线程通知,满足通知数量后主线程会继续执行;
CyclicBarrier:每个线程都阻塞,当全部阻塞(某一任务完成)时,全部线程接着往下走别的操作。
Semaphore信号量:类似于newFixedThreadPool 只有允许数量的线程执行、其余在队列中等待。
ReentrantLock:重入锁 多个condition
ReentrantReadWriteLock :读读共享 读写互斥 写写互斥
Distruptor框架