java使用局部线程池为何会形成线程泄露

java使用局部线程池为何会形成线程泄露

 

1、思考 - 形成泄露,确定是没法被GC回收,那为何局部线程池没有被回收,咱们来经过源码一探究竟

   这里先给出结论:ThreadPoolExecutor  ->   Worker   ->  Thread    因为存在这样的引用关系,而且 Thread 做为 GC Root ,因此没法被回收

2、经过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

   

  

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

相关文章
相关标签/搜索