Java踩坑记系列之线程池

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"线程池大家都很熟悉,无论是平时的业务开发还是框架中间件都会用到,大部分都是基于JDK线程池","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor","attrs":{}}],"attrs":{}},{"type":"text","text":"做的封装,比如tomcat的线程池,当然也有单独开发的,但都会牵涉到这几个核心参数的设置:","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"核心线程数","attrs":{}},{"type":"text","text":",","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"等待队列","attrs":{}},{"type":"text","text":",","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"最大线程数","attrs":{}},{"type":"text","text":",","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"拒绝策略","attrs":{}},{"type":"text","text":"等。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"先说下我们项目组在使用线程池时踩到的坑:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":null,"normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"线程池的参数设置一定要结合具体的业务场景,区分I/O密集和CPU密集,如果是I/O密集型业务,核心线程数,","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"workQueue","attrs":{}}],"attrs":{}},{"type":"text","text":"等待队列,最大线程数等参数设置不合理不仅不能发挥线程池的作用,反而会影响现有业务","attrs":{}}]}],"attrs":{}},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"等待队列","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"workQueue","attrs":{}}],"attrs":{}},{"type":"text","text":"填满后,新创建的线程会优先处理新请求进来的任务,而不是去处理队列里的任务,队列里的任务只能等核心线程数忙完了才能被执行。有可能造成队列里的任务长时间等待,导致队列积压,尤其是I/O密集场景","attrs":{}}]}],"attrs":{}},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"如果需要得到线程池里的线程执行结果,使用","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future","attrs":{}}],"attrs":{}},{"type":"text","text":"的方式,拒绝策略不能使用","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"DiscardPolicy","attrs":{}}],"attrs":{}},{"type":"text","text":",这种丢弃策略虽然不执行子线程的任务,但是还是会返回","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future","attrs":{}}],"attrs":{}},{"type":"text","text":"对象(其实在这种情况下我们已经不需要线程池返回的结果了),然后后续代码即使判断了","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future!=null","attrs":{}}],"attrs":{}},{"type":"text","text":"也没用,这样的话还是会走到","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future.get()","attrs":{}}],"attrs":{}},{"type":"text","text":"方法,如果get方法没有设置超时时间会导致一直阻塞下去!","attrs":{}}]}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"伪代码如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"// 如果线程池已满,新的请求会直接执行拒绝策略\nFuture future = executor.submit(() -> {\n // 业务逻辑,比如调用第三方接口等耗时操作放在线程池里执行\n return result;\n});\n\n// 主流程调用逻辑\nif(future != null) // 如果拒绝策略设置不合理还是会走到下面代码\n future.get(超时时间); // 调用方阻塞等待结果返回,直到超时","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面就结合实际业务情况逐一进行分析。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当然这些问题一部分是对线程池理解不够导致的,还有一部分是线程池本身的问题。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"一. 背景","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"公司有个接口部分功能使用了线程池,这个功能不依赖核心接口,但有一定的耗时,所以放在线程池里和主线程并行执行,等线程池里的任务执行完通过","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future.get","attrs":{}}],"attrs":{}},{"type":"text","text":"的方式获取线程池里的线程执行结果,然后合并到主流程的结果里返回给前端,业务场景很简单,大致流程如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/de/debc640489b0cea1eddac695b75156ca.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"初衷也是为了不影响主流程的性能,不增加整体响应时间。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"但是之前使用的线程池jdk的","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"newCachedThreadPool","attrs":{}}],"attrs":{}},{"type":"text","text":",因为sonar扫描提示说有内存溢出的风险(最大线程数是","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"Integer.MAX_VALUE","attrs":{}}],"attrs":{}},{"type":"text","text":")所以当时改成使用原生的","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor","attrs":{}}],"attrs":{}},{"type":"text","text":",通过指定核心线程数和最大线程数,来解决sonar问题。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"但是改过的线程池并不适合我们这种I/O密集型的业务场景(大部分业务都是通过调用接口实现的),当时设置的核心线程数是cpu核数(线上机器是4核),等待队列是2048,最大线程数是cpu核数*2,从而引发了一系列问题。。。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"二. 排查过程","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上线后的现象是使用线程池的接口整体响应时间变长,有的甚至到10秒才返回数据,通过线程dump分析发现有大量的线程都阻塞在","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future.get","attrs":{}}],"attrs":{}},{"type":"text","text":"方法上,如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/9e/9e5c7ec561e1473ce99a59e8c585608e.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"future.get","attrs":{}}],"attrs":{}},{"type":"text","text":"方法会阻塞当前主流程,在超时时间内等待子线程返回结果,如果超时还没结果则结束等待继续执行后续的代码,超时时间设置的是默认接口超时时间10秒(后面已改为200ms),至此可以确定接口总耗时是因为流程都卡在了","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future.get","attrs":{}}],"attrs":{}},{"type":"text","text":"这一步了。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"但这不是根本原因,","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future","attrs":{}}],"attrs":{}},{"type":"text","text":"是线程池返回的,伪代码如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"Future future = executor.submit(() -> {\n // 业务逻辑,比如调用第三方接口等耗时操作放在线程池里执行\n return result;\n});","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过上面的代码可知","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future","attrs":{}}],"attrs":{}},{"type":"text","text":"没有结果的原因是提交到线程池里的任务迟迟没有被执行。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"那为什么没有执行呢?继续分析线程池的dump文件发现,线程池里的线程数已达到最大数量,满负荷运行,如图:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/f7/f74edd36d449fd6f75cbcecb906c92d1.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"SubThread","attrs":{}}],"attrs":{}},{"type":"text","text":"是我们自己定义的线程池里线程的名字,8个线程都是runnable状态,说明等待队列里已经塞满任务了,之前设置的队列长度是2048,也就是说还有2048个任务等待执行,这无疑加剧了整个接口的耗时。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"线程池的执行顺序是:","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"核心线程数","attrs":{}},{"type":"text","text":" -> ","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"等待队列","attrs":{}},{"type":"text","text":" -> ","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"最大线程数","attrs":{}},{"type":"text","text":" -> ","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"拒绝策略","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果对线程dump分析不太了解的可以看下之前的一篇文章:","attrs":{}},{"type":"link","attrs":{"href":"http://javakk.com/176.html","title":null},"content":[{"type":"text","text":"Windows环境下如何进行线程dump分析","attrs":{}}]},{"type":"text","text":",虽然环境不一样但原理类似。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里基本确定接口耗时变长的主要原因是线程池设置不合理导致的。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"另外还有一些偶发问题,就是线上日志显示虽然线程池执行了,但是线程池里的任务却没有记录运行日志,线程池里的任务是调用另外一个服务的接口,和对方接口负责人确认也确实调用了他们的接口,可我们自己的日志里却没有记录下调用报文,经过进一步查看代码发现当时的线程池拒绝策略也被修改过,并不是默认的抛出异常不执行策略","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"AbortPolicy","attrs":{}}],"attrs":{}},{"type":"text","text":",而是设置的","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"CallerRunsPolicy","attrs":{}}],"attrs":{}},{"type":"text","text":"策略,即交给调用方执行!","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/fc/fc2d291f30a7d53bf6b752b03ed6553f.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/76/765ba86f1796bf2d1fd415650089ef9d.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"也就是说当线程池达到最大负荷时执行的拒绝策略是","attrs":{}},{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"让主流程去执行提交到线程池里的任务,这样除了进一步加剧整个接口的耗时外,还会导致主流程被hang死,最关键的是无法确定是在哪一步执行提交到线程池的任务","attrs":{}},{"type":"text","text":"。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"分析日志埋点可以推断出调用的时间点应该是已经调用完了记录日志的方法,要返回给前端结果的时才执行线程池里任务,此时记录日志的方法已调用过,不会再去打印日志了,而且子任务返回的结果也无法合并到主流程结果里,因为合并主流程结果和线程池任务返回结果的方法也在之前调用过,不会回过头来再调用了,大致流程如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/1c/1cdb12c126f1318513a8aa6d1f9cd5ce.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其实这种拒绝策略并不适合我们现在的业务场景,因为线程池里的任务不是核心任务,不应该影响主流程的执行。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"三. 改进","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":null,"normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"调整线程池参数,核心线程数基于线上接口的QPS计算,最大线程数参考线上tomcat的最大线程数配置,能够cover住高峰流量,队列设置的尽量小,避免造成任务挤压。关于线程数如何设置会在后续文章中单独讲解。","attrs":{}}]}],"attrs":{}},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"扩展线程池,封装原生JDK线程池","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"ThreadPoolExecutor","attrs":{}}],"attrs":{}},{"type":"text","text":",增加对线程池各项指标的监控,包括线程池运行状态、核心线程数、最大线程数、任务等待数、已完成任务数、线程池异常关闭等信息,便于实时监控和定位问题。","attrs":{}}]}],"attrs":{}},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"重写线程池拒绝策略,主要也是记录超出线程池负载情况下的各项指标情况,以及调用线程的堆栈信息,便于排查分析,通过抛出异常方式中断执行,避免引用的","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future","attrs":{}}],"attrs":{}},{"type":"text","text":"不为null的问题。","attrs":{}}]}],"attrs":{}},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"合理调整","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"future.get","attrs":{}}],"attrs":{}},{"type":"text","text":"超时时间,防止阻塞主线程时间过长。","attrs":{}}]}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"线程池内部流程:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/d4/d4456c06c156d97baa74f3064f8e2ebc.png","alt":"image","title":"image","style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"线程池监控和自定义拒绝策略的代码如下,大家可以结合自己的业务场景拿去使用:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"package com.javakk;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.text.MessageFormat;\nimport java.util.List;\nimport java.util.concurrent.*;\n\n/**\n * 自定义线程池

\n * 1.监控线程池状态及异常关闭等情况

\n * 2.监控线程池运行时的各项指标, 比如:任务等待数、已完成任务数、任务异常信息、核心线程数、最大线程数等

\n * author: 老K\n */\npublic class ThreadPoolExt extends ThreadPoolExecutor{\n\n private static final Logger log = LoggerFactory.getLogger(ThreadPoolExt.class);\n\n private TimeUnit timeUnit;\n\n public ThreadPoolExt(int corePoolSize,\n int maximumPoolSize,\n long keepAliveTime,\n TimeUnit unit,\n BlockingQueue workQueue,\n ThreadFactory threadFactory,\n RejectedExecutionHandler handler) {\n super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);\n this.timeUnit = unit;\n }\n\n @Override\n public void shutdown() {\n // 线程池将要关闭事件,此方法会等待线程池中正在执行的任务和队列中等待的任务执行完毕再关闭\n monitor(\"ThreadPool will be shutdown:\");\n super.shutdown();\n }\n\n @Override\n public List shutdownNow() {\n // 线程池立即关闭事件,此方法会立即关闭线程池,但是会返回队列中等待的任务\n monitor(\"ThreadPool going to immediately be shutdown:\");\n // 记录被丢弃的任务, 暂时只记录日志, 后续可根据业务场景做进一步处理\n List dropTasks = null;\n try {\n dropTasks = super.shutdownNow();\n log.error(MessageFormat.format(\"ThreadPool discard task count:{0}\", dropTasks.size()));\n } catch (Exception e) {\n log.error(\"ThreadPool shutdownNow error\", e);\n }\n return dropTasks;\n }\n\n @Override\n protected void beforeExecute(Thread t, Runnable r) {\n // 监控线程池运行时的各项指标\n monitor(\"ThreadPool monitor data:\");\n }\n\n @Override\n protected void afterExecute(Runnable r, Throwable ex) {\n if (ex != null) { // 监控线程池中的线程执行是否异常\n log.error(\"unknown exception caught in ThreadPool afterExecute:\", ex);\n }\n }\n\n /**\n * 监控线程池运行时的各项指标, 比如:任务等待数、任务异常信息、已完成任务数、核心线程数、最大线程数等

\n */\n private void monitor(String title){\n try {\n // 线程池监控信息记录, 这里需要注意写ES的时机,尤其是多个子线程的日志合并到主流程的记录方式\n String threadPoolMonitor = MessageFormat.format(\n \"{0}{1}core pool size:{2}, current pool size:{3}, queue wait size:{4}, active count:{5}, completed task count:{6}, \" +\n \"task count:{7}, largest pool size:{8}, max pool size:{9}, keep alive time:{10}, is shutdown:{11}, is terminated:{12}, \" +\n \"thread name:{13}{14}\",\n System.lineSeparator(), title, this.getCorePoolSize(), this.getPoolSize(),\n this.getQueue().size(), this.getActiveCount(), this.getCompletedTaskCount(), this.getTaskCount(), this.getLargestPoolSize(),\n this.getMaximumPoolSize(), this.getKeepAliveTime(timeUnit != null ? timeUnit : TimeUnit.SECONDS), this.isShutdown(),\n this.isTerminated(), Thread.currentThread().getName(), System.lineSeparator());\n log.info(threadPoolMonitor);\n } catch (Exception e) {\n log.error(\"ThreadPool monitor error\", e);\n }\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"自定义拒绝策略代码:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"package com.javakk;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.lang.management.*;\nimport java.text.MessageFormat;\nimport java.util.concurrent.RejectedExecutionException;\nimport java.util.concurrent.RejectedExecutionHandler;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * 自定义线程池拒绝策略:

\n * 1.记录线程池的核心线程数,活跃数,已完成数等信息,以及调用线程的堆栈信息,便于排查

\n * 2.抛出异常中断执行

\n * author: 老K\n */\npublic class RejectedPolicyWithReport implements RejectedExecutionHandler {\n\n private static final Logger log = LoggerFactory.getLogger(RejectedPolicyWithReport.class);\n\n private static volatile long lastPrintTime = 0;\n\n private static final long TEN_MINUTES_MILLS = 10 * 60 * 1000;\n\n private static Semaphore guard = new Semaphore(1);\n @Override\n public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {\n try {\n String title = \"thread pool execute reject policy!!\";\n String msg = MessageFormat.format(\n \"{0}{1}core pool size:{2}, current pool size:{3}, queue wait size:{4}, active count:{5}, completed task count:{6}, \" +\n \"task count:{7}, largest pool size:{8}, max pool size:{9}, keep alive time:{10}, is shutdown:{11}, is terminated:{12}, \" +\n \"thread name:{13}{14}\",\n System.lineSeparator(), title, e.getCorePoolSize(), e.getPoolSize(), e.getQueue().size(), e.getActiveCount(),\n e.getCompletedTaskCount(), e.getTaskCount(), e.getLargestPoolSize(), e.getMaximumPoolSize(), e.getKeepAliveTime(TimeUnit.SECONDS),\n e.isShutdown(), e.isTerminated(), Thread.currentThread().getName(), System.lineSeparator());\n log.info(msg);\n threadDump(); // 记录线程堆栈信息包括锁争用信息\n } catch (Exception ex) {\n log.error(\"RejectedPolicyWithReport rejectedExecution error\", ex);\n }\n throw new RejectedExecutionException(\"thread pool execute reject policy!!\");\n }\n\n /**\n * 获取线程dump信息

\n * 注意: 该方法默认会记录所有线程和锁信息虽然方便debug, 使用时最好加开关和间隔调用, 否则可能会增加latency

\n * 1.当前线程的基本信息:id,name,state

\n * 2.堆栈信息

\n * 3.锁相关信息(可以设置不记录)

\n * 默认在log记录

\n * @return\n */\n private void threadDump() {\n long now = System.currentTimeMillis();\n // 每隔10分钟dump一次\n if (now - lastPrintTime < TEN_MINUTES_MILLS) { \n return; \n } \n if (!guard.tryAcquire()) { \n return; \n } \n // 异步dump线程池信息 \n ExecutorService pool = Executors.newSingleThreadExecutor(); \n pool.execute(() -> {\n try {\n ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();\n StringBuilder sb = new StringBuilder();\n for (ThreadInfo threadInfo : threadMxBean.dumpAllThreads(true, true)) {\n sb.append(getThreadDumpString(threadInfo));\n }\n log.error(\"thread dump info:\", sb.toString());\n } catch (Exception e) {\n log.error(\"thread dump error\", e);\n } finally {\n guard.release();\n }\n lastPrintTime = System.currentTimeMillis();\n });\n pool.shutdown();\n }\n\n @SuppressWarnings(\"all\")\n private String getThreadDumpString(ThreadInfo threadInfo) {\n StringBuilder sb = new StringBuilder(\"\"\" + threadInfo.getThreadName() + \"\"\" +\n \" Id=\" + threadInfo.getThreadId() + \" \" +\n threadInfo.getThreadState());\n if (threadInfo.getLockName() != null) {\n sb.append(\" on \" + threadInfo.getLockName());\n }\n if (threadInfo.getLockOwnerName() != null) {\n sb.append(\" owned by \"\" + threadInfo.getLockOwnerName() +\n \"\" Id=\" + threadInfo.getLockOwnerId());\n }\n if (threadInfo.isSuspended()) {\n sb.append(\" (suspended)\");\n }\n if (threadInfo.isInNative()) {\n sb.append(\" (in native)\");\n }\n sb.append('n');\n int i = 0;\n\n StackTraceElement[] stackTrace = threadInfo.getStackTrace();\n MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors();\n for (; i < stackTrace.length && i < 32; i++) {\n StackTraceElement ste = stackTrace[i];\n sb.append(\"tat \" + ste.toString());\n sb.append('n');\n if (i == 0 && threadInfo.getLockInfo() != null) {\n Thread.State ts = threadInfo.getThreadState();\n switch (ts) {\n case BLOCKED:\n sb.append(\"t- blocked on \" + threadInfo.getLockInfo());\n sb.append('n');\n break;\n case WAITING:\n sb.append(\"t- waiting on \" + threadInfo.getLockInfo());\n sb.append('n');\n break;\n case TIMED_WAITING:\n sb.append(\"t- waiting on \" + threadInfo.getLockInfo());\n sb.append('n');\n break;\n default:\n }\n }\n\n for (MonitorInfo mi : lockedMonitors) {\n if (mi.getLockedStackDepth() == i) {\n sb.append(\"t- locked \" + mi);\n sb.append('n');\n }\n }\n }\n if (i < stackTrace.length) {\n sb.append(\"t...\");\n sb.append('n');\n }\n\n LockInfo[] locks = threadInfo.getLockedSynchronizers();\n if (locks.length > 0) {\n sb.append(\"ntNumber of locked synchronizers = \" + locks.length);\n sb.append('n');\n for (LockInfo li : locks) {\n sb.append(\"t- \" + li);\n sb.append('n');\n }\n }\n sb.append('n');\n return sb.toString();\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文章来源:","attrs":{}},{"type":"link","attrs":{"href":"http://javakk.com/188.html","title":null},"content":[{"type":"text","text":"http://javakk.com/188.html","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章