ThreadLocal内存泄漏分析
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
引言
ThreadLocal内存泄漏的原因
代码验证
package quickstart;
import java.util.ArrayList;
import java.util.List;
public class TestThreadLocalMemoryLeak {
public static void main(String[] args) {
ttt(null);
while (true){
try{
Thread.sleep(1000 * 2);
}catch (Exception e){
e.printStackTrace();
}
}
}
public static void ttt(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("==================");
leak();
try{
Thread.sleep(1000 * 60);
}catch (Exception e){
e.printStackTrace();
}
}
private void leak(){
List<Double> list = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
ThreadLocal<List> listThreadLocal
= new ThreadLocal<>();
listThreadLocal.set(list);
}
};
Thread thread = new Thread(runnable);
System.out.println("thread start");
thread.start();
try{
thread.join();
}catch (Exception e){
e.printStackTrace();
}
System.out.println("thread end");
}
}
你能明白下面的程序为啥不会构成内存泄漏吗?
package quickstart;
import java.util.ArrayList;
import java.util.List;
public class TestThreadLocalMemoryLeak {
public static void main(String[] args) {
ttt(null);
}
public static void ttt(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("==================");
leak();
try{
Thread.sleep(1000 * 60);
}catch (Exception e){
e.printStackTrace();
}
}
private void leak(){
List<Double> list = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
ThreadLocal<List> listThreadLocal
= new ThreadLocal<>();
listThreadLocal.set(list);
}
};
Thread thread = new Thread(runnable);
System.out.println("thread start");
thread.start();
try{
thread.join();
}catch (Exception e){
e.printStackTrace();
}
System.out.println("thread end");
while (true){
try{
Thread.sleep(1000 * 2);
System.out.println(thread);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/xiaolixi199311/article/details/116565875
粉丝福利:Java从入门到入土学习路线图
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈
评论