java使用局部线程池为什么会造成线程泄露
Posted 梦灬颜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java使用局部线程池为什么会造成线程泄露相关的知识,希望对你有一定的参考价值。
java使用局部线程池为什么会造成线程泄露
一、思考 - 造成泄露,肯定是无法被GC回收,那为什么局部线程池没有被回收,我们来通过源码一探究竟
这里先给出结论:ThreadPoolExecutor -> Worker -> Thread 由于存在这样的引用关系,并且 Thread 作为 GC Root ,所以无法被回收
二、通过ThreadPoolExecutor类对源码一探究竟 不详解
ExecutorService threadPool = new ThreadPoolExecutor( 1, 1, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1), Executors.defaultThreadFactory() ); threadPool.execute(() -> { System.out.println("sdf"); });
1.进入threadPool.execute()方法,如下图
图1
2.重点是addWorker方法,不废话,直接进入图1红色框addWorker(command, true) 这个方法
图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
图3
图4
3.2 第二步是提取出 Worker 实例的 Thread,也就是第一步getThreadFactory().newThread(this) new 出来的线程
3.3 第三步就是直接执行 Worker 实例的 Thread,到这里我们很清晰的知道了,线程池里的线程最后执行的是Worker 而不是 调用者传进来的Runnable
4. 重点来了,追一下Worker的 run方法,一切将大白于天下
图5
4.1 分析图6可知,最终执行还是 (调用者)传进来的Runnable,但是有一个问题Thread 执行完Runnable后并不会stop,而是会进入阻塞,见 红色框1 进入 getTask()方法一探
图6
4.2 从图7可以看出
4.2.1.若有数据 -> 则会返回Runnable 任务进入图6中的while循环中执行
4.2.2.若没有数据 -> 则会阻塞(看图7红色框), 愿意的可以去看看juc中的阻塞队列的实现,就能知道阻塞的原理了,这不再此次范围内
图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 class JVMDemoTest { public static void main(String[] args) throws Exception { JVMDemoTest t = new JVMDemoTest(); while (true) { Thread.sleep(1000); t.test(); } } private void test() { for (int i = 0; i < 10; i++) { Executor mExecutors = Executors.newFixedThreadPool(3); for (int j = 0; j < 3; j++) { mExecutors.execute(new Runnable() { @Override public void run() { System.out.println("execute"); } }); } } } }
6.2 使用jdk 自带的工具 jvisualvm 监控线程如下(堆的最低点是多次执行GC导致的),可见线程一直向上飙升
6.3 使用jmap -dump:format=b,file=aaaa.hprof 46008 命令 dump 堆下来分析。我使用的分析工具是MAT
使用直方图打开,可以看到 ThreadPoolExecutor对象 有 640个,Worker对象有1923个,充分的说明 线程池并没有被GC 回收
我们使用MAT提供的查看GC Root 工具查看如图11. 从图中可知 Thread 确实是GC Root 对象
图11
鄙人小白,若有分析不到之处,望指正
以上是关于java使用局部线程池为什么会造成线程泄露的主要内容,如果未能解决你的问题,请参考以下文章