ThreadLocal內(nèi)存泄漏分析
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
76套java從入門(mén)到精通實(shí)戰(zhàn)課程分享
引言
ThreadLocal內(nèi)存泄漏的原因
代碼驗(yàn)證
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");
}
}
你能明白下面的程序?yàn)樯恫粫?huì)構(gòu)成內(nèi)存泄漏嗎?
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();
}
}
}
}
版權(quán)聲明:本文為博主原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接和本聲明。
本文鏈接:
https://blog.csdn.net/xiaolixi199311/article/details/116565875
粉絲福利:Java從入門(mén)到入土學(xué)習(xí)路線圖
??????

??長(zhǎng)按上方微信二維碼 2 秒
感謝點(diǎn)贊支持下哈 
評(píng)論
圖片
表情


