教程:https://www.bilibili.com/video/BV1ar4y1x727?p=100
ThreadLocal 和 TreadLocalMap 数据结构关系?
ThreadLocal 中的 key 是弱引用,为什么?
ThreadLocal 内存泄漏问题是什么?
ThreadLocal 中最后为什么要加 remove 方法?
ThreadLocal 提供线程局部变量。这些变量与正常的变量不同,因为每个线程在访问 ThreadLocal 实例的时候(通过 get 或 set 方法)都有自己的、独立初始化的变量副本。ThreadLocal 实例通常是类中的私有静态字段,使用它的目的是希望将状态(例如,用户 ID 或事务 ID)与线程关联起来。
实例方法上锁
@Slf4j(topic = "c.Test")
public class Test {
public static void main(String[] args) {
House house = new House();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
int size = new Random().nextInt(10) + 1;
log.info("{} 卖出了 {} 套房子", Thread.currentThread().getName(), size);
for (int j = 0; j < size; j++) {
house.saleHouse();
}
}, "t" + i).start();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("{} 共卖出了 {} 套房子", Thread.currentThread().getName(), house.saleCount);
}
}
class House {
public int saleCount;
public synchronized void saleHouse() {
saleCount++;
}
}
@Slf4j(topic = "c.Test")
public class Test {
public static void main(String[] args) {
House house = new House();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
int size = new Random().nextInt(10) + 1;
for (int j = 0; j < size; j++) {
house.saleVolumeByThreadLocal();
}
log.info("{} 卖出了 {} 套房子", Thread.currentThread().getName(), house.saleVolume.get());
}, "t" + i).start();
}
}
}
class House {
ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);
public void saleVolumeByThreadLocal() {
saleVolume.set(saleVolume.get() + 1);
}
}
这样写的隐患:
线程池的场景下因为线程会复用,如果不清理自定义的 ThreadLocal 变量,可能会影响后续业务逻辑和造成内存泄漏等问题。尽量在代理中使用 try-finally
块进行回收。
try {
int size = new Random().nextInt(10) + 1;
for (int j = 0; j < size; j++) {
house.saleVolumeByThreadLocal();
}
log.info("{} 卖出了 {} 套房子", Thread.currentThread().getName(), house.saleVolume.get());
} finally {
house.saleVolume.remove();
}
@Slf4j(topic = "c.Test")
public class Test {
public static void main(String[] args) {
MyData myData = new MyData();
ExecutorService threadPool = Executors.newFixedThreadPool(3);
try {
for (int i = 0; i < 10; i++) {
threadPool.submit(() -> {
Integer before = myData.threadLocalField.get();
myData.add();
Integer after = myData.threadLocalField.get();
log.info("before: {} -> after: {}", before, after);
});
}
} finally {
threadPool.shutdown();
}
}
}
class MyData {
public ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(() -> 0);
public void add() {
threadLocalField.set(threadLocalField.get() + 1);
}
}
每个线程每执行完自己的任务后就应该恢复到原始状态,否则会影响到后续的线程。
@Slf4j(topic = "c.Test")
public class Test {
public static void main(String[] args) {
MyData myData = new MyData();
ExecutorService threadPool = Executors.newFixedThreadPool(3);
try {
for (int i = 0; i < 10; i++) {
threadPool.submit(() -> {
try {
Integer before = myData.threadLocalField.get();
myData.add();
Integer after = myData.threadLocalField.get();
log.info("before: {} -> after: {}", before, after);
} finally {
// 清除线程变量
myData.threadLocalField.remove();
}
});
}
} finally {
threadPool.shutdown();
}
}
}
class MyData {
public ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(() -> 0);
public void add() {
threadLocalField.set(threadLocalField.get() + 1);
}
}
ThreadLocalMap
从字面上可以看出这是一个保存 ThreadLocal
对象的 map,以 ThreadLocal
为 key。
JVM 内部维护了一个线程版的 Map
,(通过 ThreadLocal
对象的 set 方法,结果把 ThreadLocal
对象自己当作 key,放进了 ThreadLocalMap
中),每个线程要用到这个线程的时候,用当前的线程去 Map 中获取,通过这样让每个线程都有了自己独立的变量,人手一份,竞争条件被彻底消除,在并发模式下是绝对安全的变量。
内存泄漏:占着茅坑不拉屎,不再使用的对象占用的内存不能被回收。
为什么要用弱引用?
To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys. However, since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space.
ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(() -> 0);