记一次数据库连接池内存泄漏问题的分析和解决方案[转]
问题描述
上周五晚上某核心服务出现大量超时,经过查看日志发现是由于出现长时间gc导致的。
- GC时间接近1s,当大量并发的时候会导致服务处理超时
- GC大概每7天出现一次,只是今天业务大幅上涨,感知才会更加明显
然后紧急把剩余未gc的一个节点内存dump下来,使用mat工具打开发现,com.mysql.jdbc.NonRegisteringDriver 对象占了堆内存的大部分空间。
查看对象数量,发现com.mysql.jdbc.NonRegisteringDriver$ConnectionPhantomReference 这个对象堆积了10140 个。
初步判断长时间gc的问题应该是由于 com.mysql.jdbc.NonRegisteringDriver$ConnectionPhantomReference 这个对象大量堆积引起的。
问题分析
目前正式环境使用数据库相关依赖如下:
|依赖|版本
|——
|mysql|5.1.47
|hikari|2.7.9
|Sharding-jdbc|3.1.0
根据以上描述,提出以下问题:
1、com.mysql.jdbc.NonRegisteringDriver$ConnectionPhantomReference 到底是个什么对象呢?- 2、这种对象为什么会大量堆积,JVM回收不过来了?
NonRegisteringDriver$ConnectionPhantomReference 到底是个什么对象呢?
简单来说,NonRegisteringDriver类有个虚引用集合connectionPhantomRefs用于存储所有的数据库连接,NonRegisteringDriver.trackConnection方法负责把新创建的连接放入connectionPhantomRefs集合。源码如下:
public class NonRegisteringDriver implements java.sql.Driver {
protected static final ConcurrentHashMap<ConnectionPhantomReference, ConnectionPhantomReference> connectionPhantomRefs = new ConcurrentHashMap<ConnectionPhantomReference, ConnectionPhantomReference>();
protected static final ReferenceQueue<ConnectionImpl> refQueue = new ReferenceQueue<ConnectionImpl>();
....
protected static void trackConnection(Connection newConn) {
ConnectionPhantomReference phantomRef = new ConnectionPhantomReference((ConnectionImpl) newConn, refQueue);
connectionPhantomRefs.put(phantomRef, phantomRef);
}
....
}
我们追踪创建数据库连接的过程源码,发现其中会调到com.mysql.jdbc.ConnectionImpl的构造函数,该方法会调用createNewIO方法创建一个新的数据库连接MysqlIO对象,然后调用我们上面提到的NonRegisteringDriver.trackConnection方法,把该对象放入NonRegisteringDriver.connectionPhantomRefs集合。源码如下:
public class ConnectionImpl extends ConnectionPropertiesImpl implements MySQLConnection {
public ConnectionImpl(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url) throws SQLException {
...
createNewIO(false);
...
NonRegisteringDriver.trackConnection(this);
...
}
}
connectionPhantomRefs 是一个虚引用集合,何为虚引用?为什么设计为虚引用队列
虚引用队列也称为“幽灵引用”,它是最弱的一种引用关系。- 如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃 圾回收器回收。- 为一个对象设置虚 引用关联的唯一目的只是为了能在这个对象被收集器回收时收到一个系统通知。- 当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在垃圾回收后,将这个虚引用加入引用队列,在其关联的虚引用出队前,不会彻底销毁该对象。所以可以通过检查引用队列中是否有相应的虚引用来判断对象是否已经被回收了。
connectionPhantomRefs 这种对象为什么会大量堆积,JVM回收不过来了?
这里结合项目中hikaricp数据配置和官方文档结合说明~
我们先查阅hikaricp数据池的官网地址,看看部分属性介绍如下:
maximumPoolSize
This property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. A reasonable value for this is best determined by your execution environment. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. Please read about pool sizing. Default: 10
maximumPoolSize控制最大连接数,默认为10
minimumIdle
This property controls the minimum number of idle connections that HikariCP tries to maintain in the pool. If the idle connections dip below this value and total connections in the pool are less than maximumPoolSize, HikariCP will make a best effort to add additional connections quickly and efficiently. However, for maximum performance and responsiveness to spike demands, we recommend not setting this value and instead allowing HikariCP to act as a fixed size connection pool. Default: same as maximumPoolSize
minimumIdle控制最小连接数,默认等同于maximumPoolSize,10。
⌚idleTimeout
This property controls the maximum amount of time that a connection is allowed to sit idle in the pool. This setting only applies when minimumIdle is defined to be less than maximumPoolSize. Idle connections will not be retired once the pool reaches minimumIdle connections. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. The minimum allowed value is 10000ms (10 seconds). Default: 600000 (10 minutes)
连接空闲时间超过idleTimeout(默认10分钟)后,连接会被抛弃
⌚maxLifetime
This property controls the maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. On a connection-by-connection basis, minor negative attenuation is applied to avoid mass-extinction in the pool. We strongly recommend setting this value, and it should be several seconds shorter than any database or infrastructure imposed connection time limit. A value of 0 indicates no maximum lifetime (infinite lifetime), subject of course to the idleTimeout setting. Default: 1800000 (30 minutes)
连接生存时间超过 maxLifetime(默认30分钟)后,连接会被抛弃.
我们再回头看看项目的hikari配置:
配置了minimumIdle = 10,maximumPoolSize = 50,没有配置idleTimeout和maxLifetime。所以这两项会使用默认值 idleTimeout = 10分钟,maxLifetime = 30分钟。- 也就是说假如数据库连接池已满,有50个连接,假如系统空闲,40个连接会在10分钟后(超过idleTimeout)被废弃;假如系统一直繁忙,50个连接会在30分钟后(超过maxLifetime)后被废弃。
猜测问题产生的根源:
每次新建一个数据库连接,都会把该连接放入connectionPhantomRefs集合中。数据连接在空闲时间超过idleTimeout或生存时间超过maxLifetime后会被废弃,在connectionPhantomRefs集合中等待回收。因为连接资源一般存活时间比较久,经过多次Young GC,一般都能存活到老年代。如果这个数据库连接对象本身在老年代,connectionPhantomRefs中的元素就会一直堆积,直到下次 full gc。如果等到full gc 的时候connectionPhantomRefs集合的元素非常多,该次full gc就会非常耗时。
那么怎么解决呢?可以考虑优化minimumIdle、maximumPoolSize、idleTimeout、maxLifetime这些参数,下一小节我们分析一波
问题解决方案
由上面分析可知,问题产生的废弃的数据库连接对象堆积,最终导致 full gc 时间过长。所以我们可以从以下方面思考解决方案:
1、减少废弃的数据连接对象的产生和堆积。- 2、优化full gc时间.
【调整hikari参数】
我们可以考虑设置 maxLifetime 为一个较大的值,用于延长连接的生命周期,减少产生被废弃的数据库连接的频率,等到下次 full gc 的时候需要清理的数据库连接对象会大大减少。
Hikari 推荐 maxLifetime 设置为比数据库的 waittimeout 时间少 30s 到 1min。如果你使用的是 mysql 数据库,可以使用 show global variables like ‘%timeout%’; 查看 waittimeout,默认为 8 小时
【使用G1回收器】
G1回收器是目前java垃圾回收器的最新成果,是一款低延迟高吞吐的优秀回收器,用户可以自定义最大暂停时间目标,G1会尽可能在达到高吞吐量同时满足垃圾收集暂停时间目标。
【建立巡查系统】
这个我们目前还没有经过实践,但是根据上面分析结果判断,定期触发full gc可以达到每次清理少量堆积的数据库连接的作用,避免过多数据库连接一直堆积。采用该方法需要对业务的内容和高低峰周期非常熟悉。实现思路参考如下:
1、创建java程序,使用定时任务定期调用System.gc()。该方法的缺点是即使手动调用了System.gc(),jvm不一定会立刻开始回收工作,有可能会根据它本身的算法,自行选择最优时间才开始进行回收工作。- 2、创建shell脚本调用jmap -dump:live,file=dump001.bin PID,使用linux的crontab任务保证定时执行,执行完后再把dump001.bin删掉即可。该方法能保证一定发生full gc,缺点是功能过于单一零散,不好集中管理。
总结
我们这次问题产生的根源是数据库连接对象堆积,导致full gc时间过长。解决思路可以从以下三点入手:
- 1、调整hikari配置参数。例如把maxLifetime设置为较大的值(比数据库的wait_timeout少30s),minimumIdle和maximumPoolSize值不能设置太大,或者直接采用默认值即可。
- 2、采用G1垃圾回收器。
- 3、建立巡查系统,在业务低峰期主动触发full gc。
参考: