最近在使用netty的時候突然碰到這樣的一個警告:
2010-8-11 12:20:28 org.jboss.netty.util.internal.SharedResourceMisuseDetector
警告: You are creating too many MemoryAwareThreadPoolExecutor instances. MemoryAwareThreadPoolExecutor is a shared resource that must be reused across the application, so that only a few instances are created.
2010-8-11 12:20:28 org.jboss.netty.util.internal.SharedResourceMisuseDetector
警告: You are creating too many HashedWheelTimer instances. HashedWheelTimer is a shared resource that must be reused across the application, so that only a few instances are created.
說的是我在使用
MemoryAwareThreadPoolExecutor和HashedWheelTimer
的時候創造了太多的實例.後來一看源碼才發現問題所在!這兩個貌似都是線程池的對象,在各自的構造方法裏面,每實例一個對象就會使各自SharedResourceMisuseDetector(濫用共享資源探測器)加一.當超過256的時候就報警了!
private static final SharedResourceMisuseDetector misuseDetector =
new SharedResourceMisuseDetector(MemoryAwareThreadPoolExecutor.class);
.....
// Misuse check
misuseDetector.increase();
後來再查看HashedWheelTimer的源代碼中還發現了這樣的提示:
<h3>Do not create many instances.</h3>
*
* {@link HashedWheelTimer} creates a new thread whenever it is instantiated and
* started. Therefore, you should make sure to create only one instance and
* share it across your application. One of the common mistakes, that makes
* your application unresponsive, is to create a new instance in
* {@link ChannelPipelineFactory}, which results in the creation of a new thread
* for every connection.
大致就說不要創建太多的實例
之前我是這樣寫的
public class ServerPipelineFactory implements ChannelPipelineFactory {
...
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("executor", new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16, 1048576, 1048576)));
pipeline.addLast("timeout", new ReadTimeoutHandler(new HashedWheelTimer(), 10));
這樣以來每個channel獲取PipelineFactory的時候都會重新實例MemoryAwareThreadPoolExecutor和HashedWheelTimer,
當連接一多的時候就報警了!
根據這個提示我修改了ServerPipelineFactory,把他們做出單例的引用
public class ServerPipelineFactory implements ChannelPipelineFactory {
...
static OrderedMemoryAwareThreadPoolExecutor e = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0);
static HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
static ExecutionHandler executionHandler = new ExecutionHandler(e);
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("executor", executionHandler );
pipeline.addLast("timeout", new ReadTimeoutHandler(hashedWheelTimer, 10));
這樣就不會再有SharedResourceMisuseDetector的警告了!