考虑有下面的工具类:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUnits {
private final static SimpleDateFormat sdf = new SimpleDateFormat(FormatType.TYPE1.type);
public static String format(Date date){
return sdf.format(date);
}
enum FormatType{
TYPE1("yyyy-MM-dd HH:mm:ss"),
TYPE2("yyyy-MM-dd");
private String type;
private FormatType(String type){
this.type = type;
}
public String getType() {
return type;
}
}
public static void main(String[] args) {
System.out.println(DateUnits.format(new Date()));
}
}
我们知道,SimpleDateFormat的format方法不是线程安全的(主要是Calendar造成的),那么当多个线程使用这个工具时如何消除并发问题呢?当然很简单的一种方法,用sychronized即可,但是sychronized性能比较差,此时我们可以用到ThreadLocal类了,代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadLocalTest {
private static ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>(){
/*@Override
protected SimpleDateFormat initialValue() {
System.out.println("create simpledateFormat");
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}*/
};
public static void main(String[] args) {
ExecutorService ex = Executors.newCachedThreadPool();
try{
for(int i = 0;i < 5;i++){
final int j = i;
ex.execute(new Runnable(){
public void run(){
try {
TimeUnit.SECONDS.sleep(j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tl.get().format(new Date()));
}
});
}
}finally{
ex.shutdown();
}
}
}
结果:
create simpledateFormat
2018-03-25 20:56:12
create simpledateFormat
2018-03-25 20:56:13
create simpledateFormat
2018-03-25 20:56:14
create simpledateFormat
2018-03-25 20:56:15
create simpledateFormat
2018-03-25 20:56:16
每个线程都会创建自己的SimpleDateFormat对象。
下面详解一下ThreadLocal的实现机制
ThreadLocal常用方法有4个:set(T value)、get()、setInitialValue()、initialValue()
首先看一下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中set元素时,该元素最终会存入当前线程对象的ThreadLocalMap中,通过查看Thread类的源码我们发现,Thread类中维护着一个ThreadLocal.ThreadLocalMap域:ThreadLocal.ThreadLocalMap threadLocals = null; ThreadLocalMap是ThreadLocal类的一个静态内部类,其核心为一个Entry[]数组,这里的Entry不是HashMap里的Entry,而是 ThreadLocalMap类里的一个静态内部类,有些乱,贴出源码:
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
那么Thread的ThreadLocalMap成员什么时候初始化呢?这里其实也是懒加载,new Thread()并不会初始化,只有当你ThreadLocal时才会加载,看上面set方法的createMap方法便可得出此结论:
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
初始化大小16,每当Entry[]大小过2/3时会扩容,扩容会触发hash重排,这点倒是类似于HashMap(HashMap默认是超过3/4时扩容),set方法就介绍到此,总之set方法就是向当前线程对象的一个map里存放对象,由于key是ThreadLocal实例,所以你想让一个线程存放多个本地变量时,你不得不创建多个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)
return (T)e.value;
}
return setInitialValue();
}
get方法首先还是去找当前线程的ThreadLocalMap,如果找到了,然后就根据key(也就是调用get方法的ThreadLocal对象)的hash值通过运算定位到Entry[]数组中的具体元素:
private Entry getEntry(ThreadLocal key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
如果ThreadLocalMap为空呢,get方法会返回什么?仔细看我的测试代码就可以发现,我并没有调用set方法,但是get方法依然得到了想要的SimpleDateFormat,我们可以看到get方法如果发现ThreadLocalMap还没有初始化时,不会马上返回null,而是去调用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;
}
setInitialValue方法又会去调用initialValue方法:
protected T initialValue() {
return null;
}
看到这里我们可以发现默认情况下不先set而直接调用get方法的确行不通(经测试会报空指针异常),但是我们可以通过重写initialValue方法,而在现实中,我们的确应该这么做
ThreadLocal设计的精妙之处在于ThreadLocal本身不会存储任何数据,但是你要存取数据都要依赖它,遗憾的是现实开发中本人还没遇见很适合用ThreadLocal的场景(可能遇到了也没想到),不过毫无疑问它是有用武之地的,据说Spring的连接池模块很好的运用了ThreadLocal,有兴趣的同学可以深入研究一下