最近在用Netty帮助业务开发封装一个通讯组件的时候,关于ChannelFactory发现了一些问题,暂时纪录如下:
1 - 内存泄漏问题
梁飞的博客中提到了Netty的ChannelFactory在不断的销毁和创建过程中,会出现内存泄漏的问题,从而在dubbo中采用静态化的方式来规避这个问题(原文:http://javatar.iteye.com/blog/1138527)。但是我的开发环境下面(jdk1.7.0_09Mac版 + Netty 3.6.2),使用类似梁飞博客中的测试案例时,采用静态化反而会出现Can't assign requested address的错误,如果不使用静态化的方式,反而能够顺利运行(大约运行了2个小时,重复了2000多万次的创建和销毁)。
2 - java.util.concurrent.RejectedExecutionException
在心跳的测试过程中,发现Server unbound再重新bound之后,客户端无法重新连接,报了java.util.concurrent.RejectedExecutionException。开始无论如何也没想明白为什么,google之后再结合代码的改动突然想到,心跳失败后会关闭连接时会调用ChannelFactory.releaseExternalResources()的方法,重新连接时并没有再次初始化ChannelFactory对象,由于releaseExternalResources方法会调用所有executor(包括bossExecutor,workerExecutor,内部的deadlock proof executor等)的shutdown方法,这样在重新连接时向executor发送建立连接的task时就会出现异常。
P.S: java.util.concurrent.RejectedExecutionException的发生条件(from stackoverflow):
- when calling
execute()
on aThreadPoolExecutor
and the maximum pool size has been reached. - when calling
execute()
on aThreadPoolExecutor
at the same time thatshutdownNow
, and has essentially lost the race with theshutdownNow
call. - when trying to schedule execution of a runnable in a
ScheduledThreadPoolExecutor
after the executor has been shutdown.