2012-08-02 36 views
1

也许这是一个明显的问题,但我对netty来说太新了。Netty HttpChunckAggregator有状态 - >竞态条件?

看看HttpChunckAggregator类,我发现它是有状态的。这让我怀疑...给出以下管道的特定频道:

private MyServerHandler handler; 

public ChannelPipeline getPipeline() throws Exception { 
    ChannelPipeline pipeline = pipeline();     
    pipeline.addLast("decoder",new HttpRequestDecoder());  
    pipeline.addLast("chunkAggregator",new HttpChunkAggregator(4194304));  
    pipeline.addLast("encoder",new HttpResponseEncoder());    
    pipeline.addLast("chunkSeparator",new HttpChunkSeparator(4194304));   
    pipeline.addLast("handler", handler); //Singleton  
    return pipeline; 
} 

和NIO Netty的服务器,我能得到的比赛条件,分块消息和多线程的情况下?

我看到每个新通道都会创建一个新的块聚合器,但是......所有的块消息都将在同一个通道中接收到?

回答

1

它的安全性不像其他渠道所共享的那样安全。在netty中,只有一个线程正在执行上游事件,因此只要不从下游事件访问/修改这些事件,就可以安全地将状态存储在没有任何同步的字段中。

1

getPipeline为每个传入消息调用。因此,对于每个HttpRequest,您将创建一个新的HttpChunkSeparator。

如果你做了这样的事情,那完全是线程不安全的。

private MyServerHandler handler; 

// THIS IS WRONG AS getPipeline() will keep giving the same instance to multiple threads. 
private HttpChunkAggregator httpChunkAggregator; 

public ChannelPipeline getPipeline() throws Exception { 
    ChannelPipeline pipeline = pipeline();     
    pipeline.addLast("decoder",new HttpRequestDecoder()); 

    // This is WRONG. DO NO DO THIS. INSTEAD DO new HttpChunkAggregator().  
    pipeline.addLast("chunkAggregator",httpChunkAggregator);  

    pipeline.addLast("encoder",new HttpResponseEncoder());    
    pipeline.addLast("chunkSeparator",new HttpChunkSeparator(4194304));   
    pipeline.addLast("handler", handler); //Singleton  
    return pipeline; 
} 

阿伦