Netty Thread Leak?

1. Problem

我们的netty程序既是client也是server,从upstream server拿数据再提供给downstream clients。

现在的情况是运行一段时间后就不再能拿到新的数据了,所以downstream clients也只能拿到初始化数据了。

2. Analysis

2.1 Monitor and Static Analysis

用jvisualvm监控了一下动态情况,内存还比较正常,但是线程方面刚开始运行是30个左右,过了一个小时到挂的时候差不多是145个线程。这段时间内,只有4次client连接。

用jvisualvm做了一个dump以便静态分析,用的是eclipse MAT,比较方便,这145个线程中netty nio event loop就有130个线程,正好我程序里面定义了2个netty nio event loop,分别是20个和110个,这样的话所有线程都占满了,应该是线程泄露导致服务中断。但是为什么会占用掉所有线程呢?我想看看这些线程的状态,因为我感觉这些线程在某个地方阻塞了,但在MAT中好像看不到。看看代码吧

2.2 Code Review

看了一下,有几个地方值得关注:

2.2.1 channelInactive的时候没有close channel

每个channel是对应一个特定的thread,当然这个thread还可以为别的channel服务,但是既然连接都断了还是关闭一下比较好吧。

但是运行期间只连了4次,这个因素影响应该不大。

2.2.2 没有区分bossgroup和workergroup

虽然有两个group,但是要用于连接upstream和downstream,每个bootstrap里面只有一个eventgroup。

按照norman的说法,只用一个group的话,如果处理得慢了,所有线程都忙的时候就不能及时接收新的数据了,这个很像我现在的情况。

Most of the times using the same group for accepting and handling the accepted connections is working out quite well and so allows you to save some threads. The only time when you may not want to do this is if the handling logic of the accepted connections will keep the EventLoops so busy that you are not able to accept fast enough. So best is to just use the same group when you start and switch to two if you need it.

2.2.3 创建channel group用的是DefaultChannelGroup(ImmediateEventExecutor.INSTANCE)

目前还没完全搞清楚这样行不行,只是感觉有点容易出问题。

2.2.4 使用了readwritelock,可能系统中有deadlock导致线程阻塞。

2.3 Bigger View: Upstream might close the connection under certain conditions

2.4 Experiment

Reproduced this problem by unplugging/plugging the cable

奇怪的是拔掉网线后channelInactive并没有被调用,exceptionCaught也没有。可能是因为是我这个client端不发送数据,也没有加heart beat机制,所以disconnected了也不知道。

In some case netty couldnt detect if channel is closed or not. One way to solve the provlem is usingheartbeat messages. Netty supports heartbeat with IdleStateHandler.

3. Solution

使用IdleStateHandler进行reconnect,经测试稳定性高了很多, and I will keep monitoring。


Reference:

[1] http://stackoverflow.com/questions/28331809/netty-bootstrap-with-boss-group-or-with-just-with-workers-eventloopgroup

[2] http://stackoverflow.com/questions/9988343/can-netty-reliably-detect-channel-close-disconnect

[3] Netty in Action



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值