2012-08-02 77 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; 
} 

阿倫