java线程泄露_java使用局部线程池为什么会造成线程泄露

java使用局部线程池为什么会造成线程泄露

一、思考 - 造成泄露,肯定是无法被GC回收,那为什么局部线程池没有被回收,我们来通过源码一探究竟

这里先给出结论:ThreadPoolExecutor  ->   Worker   ->  Thread    由于存在这样的引用关系,并且 Thread 作为 GC Root ,所以无法被回收

二、通过ThreadPoolExecutor类对源码一探究竟  不详解

ExecutorService threadPool = newThreadPoolExecutor(1,1,300,

TimeUnit.SECONDS,new LinkedBlockingQueue<>(1),

Executors.defaultThreadFactory()

);

threadPool.execute(()->{

System.out.println("sdf");

});

1.进入threadPool.execute()方法,如下图

326a895c5c01a3bc34eb314253111997.png

图1

2.重点是addWorker方法,不废话,直接进入图1红色框addWorker(command, true) 这个方法

0dc235426291d48ad45026a81b8e2ac8.png

图2

3.关键的3步已经标出来了,看上图

3.1 先说说第一步w = new Worker(firstTask); 直接进去,从图3可以看到Worker内存有两个变量分别保存 一个待执行的Runnable和一个Thread

重点看图3红色框里的  this ,这个this 代表的Worker类的实例,也就是说线程start后执行的Runnable并不是调用者传进来的Runnable,而是Worker实例,那么可以猜测Worker是  implements Runnable 了,看图4

5e00236a7757d97474f2369667eadc36.png

图3

bcb6a1f1975066ab6196844544b51614.png

图4

3.2 第二步是提取出 Worker 实例的 Thread,也就是第一步getThreadFactory().newThread(this) new 出来的线程

3.3 第三步就是直接执行 Worker 实例的 Thread,到这里我们很清晰的知道了,线程池里的线程最后执行的是Worker 而不是 调用者传进来的Runnable

4. 重点来了,追一下Worker的 run方法,一切将大白于天下

f1effc333325c1ee5fbd1167fe51f015.png

图5

4.1 分析图6可知,最终执行还是 (调用者)传进来的Runnable,但是有一个问题Thread 执行完Runnable后并不会stop,而是会进入阻塞,见 红色框1  进入 getTask()方法一探

c8019cec802e937e054423c73f735f2e.png

图6

4.2 从图7可以看出

4.2.1.若有数据 -> 则会返回Runnable 任务进入图6中的while循环中执行

4.2.2.若没有数据  ->  则会阻塞(看图7红色框), 愿意的可以去看看juc中的阻塞队列的实现,就能知道阻塞的原理了,这不再此次范围内

1f6690d185be9908643b2372895fc6c8.png

图7

5.总结

到这里我们可以得到两个信息:

第一:为什么线程池中的线程可以复用  ---  是因为线程池中的线程执行的是Worker的Run方法,而这里面是一个相当于 while(true)的死循环,因此线程永远不会有执行完的那一天

第二:为什么不会被回收  ---    是因为存在GC ROOT 的引用,所以无法被回收 。  引用如下

ThreadPoolExecutor  ->   Worker   ->  Thread

由于Thread 是 活着的,因此可作为GC ROOT ,所以才会看到 局部线程池ThreadPoolExecutor没有被释放,可作为GC ROOT 的有以下,仅作参考

A garbage collection root is an object that is accessible from outside the heap. The following reasons make an object a GC root:

System Class

Class loaded by bootstrap/system class loader. For example, everything from the rt.jar like java.util.* .

JNI Local

Local variable in native code, such as user defined JNI code or JVM internal code.

JNI Global

Global variable in native code, such as user defined JNI code or JVM internal code.

Thread Block

Object referred to from a currently active thread block.

Thread

A started, but not stopped, thread.

Busy Monitor

Everything that has called wait() or notify() or that is synchronized. For example, by calling synchronized(Object) or by entering a synchronized method. Static method means class, non-static method means object.

Java Local

Local variable. For example, input parameters or locally created objects of methods that are still in the stack of a thread.

Native Stack

In or out parameters in native code, such as user defined JNI code or JVM internal code. This is often the case as many methods have native parts and the objects handled as method parameters become GC roots. For example, parameters used for file/network I/O methods or reflection.

Finalizable

An object which is in a queue awaiting its finalizer to be run.

Unfinalized

An object which has a finalize method, but has not been finalized and is not yet on the finalizer queue.

Unreachable

An object which is unreachable from any other root, but has been marked as a root by MAT to retain objects which otherwise would not be included in the analysis.

Java Stack Frame

A Java stack frame, holding local variables. Only generated when the dump is parsed with the preference set to treat Java stack frames as objects.

Unknown

An object of unknown root type. Some dumps, such as IBM Portable Heap Dump files, do not have root information. For these dumps the MAT parser marks objects which are have no inbound references or are unreachable from any other root as roots of this type. This ensures that MAT retains all the objects in the dump.

6.通过程序进行复现

6.1 执行的代码如下

public classJVMDemoTest {public static void main(String[] args) throwsException {

JVMDemoTest t= newJVMDemoTest();while (true) {

Thread.sleep(1000);

t.test();

}

}private voidtest() {for (int i = 0; i < 10; i++) {

Executor mExecutors= Executors.newFixedThreadPool(3);for (int j = 0; j < 3; j++) {

mExecutors.execute(newRunnable() {

@Overridepublic voidrun() {

System.out.println("execute");

}

});

}

}

}

}

6.2  使用jdk 自带的工具   jvisualvm 监控线程如下(堆的最低点是多次执行GC导致的),可见线程一直向上飙升

0db1d86596961b27529747a791fd2a73.png

6.3  使用jmap -dump:format=b,file=aaaa.hprof 46008  命令 dump 堆下来分析。我使用的分析工具是MAT

使用直方图打开,可以看到 ThreadPoolExecutor对象 有 640个,Worker对象有1923个,充分的说明 线程池并没有被GC 回收

我们使用MAT提供的查看GC Root 工具查看如图11. 从图中可知  Thread 确实是GC Root 对象

c383e931909dd970b2660c5bf8d08a5d.png

7993bc084d35390213931681178f4223.png

图11

鄙人小白,若有分析不到之处,望指正

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线程池使用ThreadLocal是为了在多线程环境下,每个线程都能够独立地访问自己的变量副本,而不受到其他线程的影响。ThreadLocal提供了一种线程局部变量的机制,使得每个线程都可以维护自己的变量副本。 在使用线程池时,我们可以通过在任务执行之前将需要共享的变量设置到ThreadLocal中,然后在任务执行期间获取该变量。这样就可以保证每个线程都能够独立地访问自己的变量副本。 下面是一个使用ThreadLocal的示例代码: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { final int index = i; executorService.execute(() -> { // 设置线程局部变量的值 threadLocal.set(index); System.out.println("Thread " + Thread.currentThread().getId() + ", value: " + threadLocal.get()); // 清除线程局部变量的值 threadLocal.remove(); }); } executorService.shutdown(); } } ``` 在上述代码中,我们创建了一个固定大小为5的线程池,并通过循环提交了10个任务。在每个任务中,我们将任务的索引存储到ThreadLocal中,并在任务执行期间获取该值并打印出来。最后,我们需要记得在任务执行结束后,清除ThreadLocal中的值,以防止内存泄漏。 通过使用ThreadLocal,每个线程都能够独立地访问自己的变量副本,从而避免了线程安全的问题,并且能够有效地利用线程池来处理多个任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值