【问题标题】:Netty HttpChunckAggregator stateful --> race conditions?Netty HttpChunckAggregator 有状态 --> 竞争条件?
【发布时间】:2012-08-02 09:45:11
【问题描述】:

也许这是一个显而易见的问题,但我对 netty 太陌生了。

查看 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 服务器,我可以在分块消息和多线程的情况下获得竞争条件吗?

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

【问题讨论】:

    标签: netty http-chunked


    【解决方案1】:

    它是安全的,因为它不被不同的频道共享。在 netty 中,只有一个线程正在执行上游事件,因此只要不从下游事件访问/修改这些状态​​,就可以安全地将状态存储在字段中而无需任何同步。

    【讨论】:

      【解决方案2】:

      每个传入消息都会调用 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;
      }
      

      阿伦

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 2010-10-09
        • 1970-01-01
        • 2023-01-30
        • 2022-01-23
        • 2018-10-08
        相关资源
        最近更新 更多