springboot中@Async默认线程池导致OOM问题
前言:
1.最近项目上在测试人员压测过程中发现了oom问题,项目使用springboot搭建项目工程,通过查看日志中包含信息:unable to create new native thread
内存溢出的三种类型:
1.第一种outofmemoryerror: permgen space,发生这种问题的原意是程序中使用了大量的jar或class
2.第二种outofmemoryerror: java heap space,发生这种问题的原因是java虚拟机创建的对象太多
3.第三种outofmemoryerror:unable to create new native thread,创建线程数量太多,占用内存过大
初步分析:
1.初步怀疑是线程创建太多导致,使用jstack 线程号 > /tmp/oom.log将应用的线程信息打印出来。查看oom.log,发现大量线程处于runnable状态,基本可以确认是线程创建太多了。
代码分析:
1.出问题的微服务是日志写库服务,对比日志,锁定在writelog方法上,wirtelog方法使用spring-@async注解,写库操作采用的是异步写入方式。
2.之前没有对@async注解深入研究过,只是知道可以自定义内部线程池,经查看,日志写库服务并未自定义异步配置,使用的是spring-@async默认异步配置
3.首先简单百度了下,网上提到@async默认异步配置使用的是simpleasynctaskexecutor,该线程池默认来一个任务创建一个线程,在压测情况下,会有大量写库请求进入日志写库服务,这时就会不断创建大量线程,极有可能压爆服务器内存。
借此机会也学习了下simpleasynctaskexecutor源码,总结如下:
1.simpleasynctaskexecutor提供了限流机制,通过concurrencylimit属性来控制开关,当concurrencylimit>=0时开启限流机制,默认关闭限流机制即concurrencylimit=-1,当关闭情况下,会不断创建新的线程来处理任务,核心代码如下:
public void execute(runnable task, long starttimeout) { assert.notnull(task, "runnable must not be null"); runnable tasktouse = (this.taskdecorator != null ? this.taskdecorator.decorate(task) : task); //判断是否开启限流机制 if (isthrottleactive() && starttimeout > timeout_immediate) { //执行前置操作,进行限流 this.concurrencythrottle.beforeaccess(); //执行完线程任务,会执行后置操作concurrencythrottle.afteraccess(),配合进行限流 doexecute(new concurrencythrottlingrunnable(tasktouse)); } else { doexecute(tasktouse); } }
2.simpleasynctaskexecutor限流实现
首先任务进来,会循环判断当前执行线程数是否超过concurrencylimit,如果超了,则当前线程调用wait方法,释放monitor对象锁,进入等待
protected void beforeaccess() { if (this.concurrencylimit == no_concurrency) { throw new illegalstateexception( "currently no invocations allowed - concurrency limit set to no_concurrency"); } if (this.concurrencylimit > 0) { boolean debug = logger.isdebugenabled(); synchronized (this.monitor) { boolean interrupted = false; while (this.concurrencycount >= this.concurrencylimit) { if (interrupted) { throw new illegalstateexception("thread was interrupted while waiting for invocation access, " + "but concurrency limit still does not allow for entering"); } if (debug) { logger.debug("concurrency count " + this.concurrencycount + " has reached limit " + this.concurrencylimit + " - blocking"); } try { this.monitor.wait(); } catch (interruptedexception ex) { // re-interrupt current thread, to allow other threads to react. thread.currentthread().interrupt(); interrupted = true; } } if (debug) { logger.debug("entering throttle at concurrency count " + this.concurrencycount); } this.concurrencycount++; } } }
2.simpleasynctaskexecutor限流实现:首先任务进来,会循环判断当前执行线程数是否超过concurrencylimit,如果超了,则当前线程调用wait方法,释放monitor对象锁,进入等待状态。
protected void beforeaccess() { if (this.concurrencylimit == no_concurrency) { throw new illegalstateexception( "currently no invocations allowed - concurrency limit set to no_concurrency"); } if (this.concurrencylimit > 0) { boolean debug = logger.isdebugenabled(); synchronized (this.monitor) { boolean interrupted = false; while (this.concurrencycount >= this.concurrencylimit) { if (interrupted) { throw new illegalstateexception("thread was interrupted while waiting for invocation access, " + "but concurrency limit still does not allow for entering"); } if (debug) { logger.debug("concurrency count " + this.concurrencycount + " has reached limit " + this.concurrencylimit + " - blocking"); } try { this.monitor.wait(); } catch (interruptedexception ex) { // re-interrupt current thread, to allow other threads to react. thread.currentthread().interrupt(); interrupted = true; } } if (debug) { logger.debug("entering throttle at concurrency count " + this.concurrencycount); } this.concurrencycount++; } } }
线程任务执行完毕后,当前执行线程数会减一,会调用monitor对象的notify方法,唤醒等待状态下的线程,等待状态下的线程会竞争monitor锁,竞争到,会继续执行线程任务。
protected void afteraccess() { if (this.concurrencylimit >= 0) { synchronized (this.monitor) { this.concurrencycount--; if (logger.isdebugenabled()) { logger.debug("returning from throttle at concurrency count " + this.concurrencycount); } this.monitor.notify(); } } }
虽然看了源码了解了simpleasynctaskexecutor有限流机制,实践出真知,我们还是测试下:
一、测试未开启限流机制下,我们启动20个线程去调用异步方法,查看java visualvm工具如下:
二、测试开启限流机制,开启限流机制的代码如下:
@configuration @enableasync public class asynccommonconfig extends asyncconfigurersupport { @override public executor getasyncexecutor() { simpleasynctaskexecutor executor = new simpleasynctaskexecutor(); //设置允许同时执行的线程数为10 executor.setconcurrencylimit(10); return executor; } }
同样,我们启动20个线程去调用异步方法,查看java visualvm工具如下:
通过上面验证可知:
1.开启限流情况下,能有效控制应用线程数
2.虽然可以有效控制线程数,但执行效率会降低,会出现主线程等待,线程竞争的情况。
3.限流机制适用于任务处理比较快的场景,对于应用处理时间比较慢的场景并不适用。==
最终解决办法:
1.自定义线程池,使用linkedblockingqueue阻塞队列来限定线程池的上限
2.定义拒绝策略,如果队列满了,则拒绝处理该任务,打印日志,代码如下:
public class asyncconfig implements asyncconfigurer{ private logger logger = logmanager.getlogger(); @value("${thread.pool.corepoolsize:10}") private int corepoolsize; @value("${thread.pool.maxpoolsize:20}") private int maxpoolsize; @value("${thread.pool.keepaliveseconds:4}") private int keepaliveseconds; @value("${thread.pool.queuecapacity:512}") private int queuecapacity; @override public executor getasyncexecutor() { threadpooltaskexecutor executor = new threadpooltaskexecutor(); executor.setcorepoolsize(corepoolsize); executor.setmaxpoolsize(maxpoolsize); executor.setkeepaliveseconds(keepaliveseconds); executor.setqueuecapacity(queuecapacity); executor.setrejectedexecutionhandler((runnable r, threadpoolexecutor exe) -> { logger.warn("当前任务线程池队列已满."); }); executor.initialize(); return executor; } @override public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() { return new asyncuncaughtexceptionhandler() { @override public void handleuncaughtexception(throwable ex , method method , object... params) { logger.error("线程池执行任务发生未知异常.", ex); } }; } }
到此这篇关于springboot中@async默认线程池导致oom问题的文章就介绍到这了,更多相关springboot @async线程池导致oom内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
下一篇: PHP实现返回JSON和XML的类分享