每一个线程须要一个独享对象(一般是工具类,典型须要使用的类有SimpleDateFormat和Random)java
每一个Thread内有本身的实例副本,不共享安全
比喻:教材只有一本,一块儿作笔记有线程安全问题。复印后没有问题,使用ThradLocal至关于复印了教材。多线程
每一个线程内须要保存全局变量(例如在拦截器中获取用户信息),可让不一样方法直接使用,避免参数传递的麻烦并发
/** * 两个线程打印日期 */
public class ThreadLocalNormalUsage00 {
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage00().date(10);
System.out.println(date);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage00().date(104707);
System.out.println(date);
}
}).start();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT 开始计时
Date date = new Date(1000 * seconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return dateFormat.format(date);
}
}
复制代码
运行结果框架
由于中国位于东八区,因此时间从1970年1月1日的8点开始计算的dom
/** * 三十个线程打印日期 */
public class ThreadLocalNormalUsage01 {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 30; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage01().date(finalI);
System.out.println(date);
}
}).start();
//线程启动后,休眠100ms
Thread.sleep(100);
}
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT 开始计时
Date date = new Date(1000 * seconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return dateFormat.format(date);
}
}
复制代码
运行结果ide
多个线程打印本身的时间(若是线程超级多就会产生性能问题),因此要使用线程池。高并发
/** * 1000个线程打印日期,用线程池来执行 */
public class ThreadLocalNormalUsage02 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
int finalI = i;
//提交任务
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage02().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT 开始计时
Date date = new Date(1000 * seconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return dateFormat.format(date);
}
}
复制代码
运行结果工具
可是使用线程池时就会发现每一个线程都有一个本身的SimpleDateFormat
对象,没有必要,因此将SimpleDateFormat
声明为静态,保证只有一个性能
/** * 1000个线程打印日期,用线程池来执行,出现线程安全问题 */
public class ThreadLocalNormalUsage03 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
//只建立一次 SimpleDateFormat 对象,避免没必要要的资源消耗
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
int finalI = i;
//提交任务
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage03().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT 开始计时
Date date = new Date(1000 * seconds);
return dateFormat.format(date);
}
}
复制代码
运行结果
出现了秒数相同的打印结果,这显然是不正确的。
出现问题的缘由
多个线程的task指向了同一个SimpleDateFormat对象,SimpleDateFormat是非线程安全的。
解决问题的方案
格式化代码是在最后一句return dateFormat.format(date);
,因此能够为最后一句代码添加synchronized
锁
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT 开始计时
Date date = new Date(1000 * seconds);
String s;
synchronized (ThreadLocalNormalUsage04.class) {
s = dateFormat.format(date);
}
return s;
}
复制代码
运行结果
运行结果中没有发现相同的时间,达到了线程安全的目的
缺点:由于添加了synchronized
,因此会保证同一时间只有一条线程能够执行,这在高并发场景下确定不是一个好的选择,因此看看其余方案吧。
/** * 利用 ThreadLocal 给每一个线程分配本身的 dateFormat 对象 * 不但保证了线程安全,还高效的利用了内存 */
public class ThreadLocalNormalUsage05 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
int finalI = i;
//提交任务
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage05().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT 开始计时
Date date = new Date(1000 * seconds);
//获取 SimpleDateFormat 对象
SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
return dateFormat.format(date);
}
}
class ThreadSafeFormatter {
public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new
ThreadLocal<SimpleDateFormat>(){
//建立一份 SimpleDateFormat 对象
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
};
}
复制代码
运行结果
使用了ThreadLocal后不一样的线程不会有共享的 SimpleDateFormat 对象,因此也就不会有线程安全问题
当前用户信息须要被线程内的全部方法共享
能够将user做为参数在每一个方法中进行传递,
缺点:可是这样作会产生代码冗余问题,而且可维护性差。
对此进行改进的方案是使用一个Map
,在第一个方法中存储信息,后续须要使用直接get()
便可,
缺点:若是在单线程环境下能够保证安全,可是在多线程环境下是不能够的。若是使用加锁和ConcurrentHashMap
都会产生性能问题。
使用 ThreadLocal 能够避免加锁产生的性能问题,也能够避免层层传递参数来实现业务需求,就能够实现不一样线程中存储不一样信息的要求。
/** * 演示 ThreadLocal 的用法2:避免参数传递的麻烦 */
public class ThreadLocalNormalUsage06 {
public static void main(String[] args) {
new Service1().process();
}
}
class Service1 {
public void process() {
User user = new User("鲁毅");
//将User对象存储到 holder 中
UserContextHolder.holder.set(user);
new Service2().process();
}
}
class Service2 {
public void process() {
User user = UserContextHolder.holder.get();
System.out.println("Service2拿到用户名: " + user.name);
new Service3().process();
}
}
class Service3 {
public void process() {
User user = UserContextHolder.holder.get();
System.out.println("Service3拿到用户名: " + user.name);
}
}
class UserContextHolder {
public static ThreadLocal<User> holder = new ThreadLocal<>();
}
class User {
String name;
public User(String name) {
this.name = name;
}
}
复制代码
运行结果
initialValue
方法仍是set
方法
initialValue
方式set
方式在Thread类内部有有ThreadLocal.ThreadLocalMap threadLocals = null;
这个变量,它用于存储ThreadLocal
,由于在同一个线程当中能够有多个ThreadLocal
,而且屡次调用get()
因此须要在内部维护一个ThreadLocalMap
用来存储多个ThreadLocal
T initialValue()
该方法用于设置初始值,而且在调用get()
方法时才会被触发,因此是懒加载。
可是若是在get()
以前进行了set()
操做,这样就不会调用initialValue()
。
一般每一个线程只能调用一次本方法,可是调用了remove()
后就能再次调用
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
//获取到了值直接返回resule
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//没有获取到才会进行初始化
return setInitialValue();
}
private T setInitialValue() {
//获取initialValue生成的值,并在后续操做中进行set,最后将值返回
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
复制代码
void set(T t)
为这个线程设置一个新值
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
复制代码
T get()
获取线程对应的value
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();
}
复制代码
void remove()
删除对应这个线程的值
内存泄露;某个对象不会再被使用,可是该对象的内存却没法被收回
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
//调用父类,父类是一个弱引用
super(k);
//强引用
value = v;
}
}
复制代码
强引用:当内存不足时触发GC,宁愿抛出OOM也不会回收强引用的内存
弱引用:触发GC后便会回收弱引用的内存
正常状况
当Thread运行结束后,ThreadLocal中的value会被回收,由于没有任何强引用了
非正常状况
当Thread一直在运行始终不结束,强引用就不会被回收,存在如下调用链
Thread-->ThreadLocalMap-->Entry(key为null)-->value
由于调用链中的 value 和 Thread 存在强引用,因此value没法被回收,就有可能出现OOM。
JDK的设计已经考虑到了这个问题,因此在set()
、remove()
、resize()
方法中会扫描到key
为null
的Entry
,而且把对应的value
设置为null
,这样value
对象就能够被回收。
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
//当ThreadLocal为空时,将ThreadLocal对应的value也设置为null
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
复制代码
可是只有在调用set()
、remove()
、resize()
这些方法时才会进行这些操做,若是没有调用这些方法而且线程不中止,那么调用链就会一直存在,因此可能会发生内存泄漏。
remove()
方法,就会删除对应的Entry
对象,能够避免内存泄漏,因此使用完ThreadLocal
后,要调用remove()
方法。class Service1 {
public void process() {
User user = new User("鲁毅");
//将User对象存储到 holder 中
UserContextHolder.holder.set(user);
new Service2().process();
}
}
class Service2 {
public void process() {
User user = UserContextHolder.holder.get();
System.out.println("Service2拿到用户名: " + user.name);
new Service3().process();
}
}
class Service3 {
public void process() {
User user = UserContextHolder.holder.get();
System.out.println("Service3拿到用户名: " + user.name);
//手动释放内存,从而避免内存泄漏
UserContextHolder.holder.remove();
}
}
复制代码
/** * ThreadLocal的空指针异常问题 */
public class ThreadLocalNPE {
ThreadLocal<Long> longThreadLocal = new ThreadLocal<>();
public void set() {
longThreadLocal.set(Thread.currentThread().getId());
}
public Long get() {
return longThreadLocal.get();
}
public static void main(String[] args) {
ThreadLocalNPE threadLocalNPE = new ThreadLocalNPE();
//若是get方法返回值为基本类型,则会报空指针异常,若是是包装类型就不会出错
System.out.println(threadLocalNPE.get());
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
threadLocalNPE.set();
System.out.println(threadLocalNPE.get());
}
});
thread1.start();
}
}
复制代码
若是get方法返回值为基本类型,则会报空指针异常,若是是包装类型就不会出错。这是由于基本类型和包装类型存在装箱和拆箱的关系,形成空指针问题的缘由在于使用者。
若是在每一个线程中ThreadLocal.set()进去的东西原本就是多个线程共享的同一对象,好比static
对象,那么多个线程调用ThreadLocal.get()
获取的内容仍是同一个对象,仍是会发生线程安全问题。
若是在任务数不多的时候,在局部方法中建立对象就能够解决问题,这样就不须要使用ThreadLocal
。
例如在Spring框架中,若是可使用RequestContextHolder
,那么就不须要本身维护ThreadLocal
,由于本身可能会忘记调用remove()
方法等,形成内存泄漏。