View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  
21  
22  /**
23   * The {@link RecvByteBufAllocator} that always yields the same buffer
24   * size prediction.  This predictor ignores the feed back from the I/O thread.
25   */
26  public class FixedRecvByteBufAllocator implements RecvByteBufAllocator {
27  
28      private static final class HandleImpl implements Handle {
29  
30          private final int bufferSize;
31  
32          HandleImpl(int bufferSize) {
33              this.bufferSize = bufferSize;
34          }
35  
36          @Override
37          public ByteBuf allocate(ByteBufAllocator alloc) {
38              return alloc.ioBuffer(bufferSize);
39          }
40  
41          @Override
42          public int guess() {
43              return bufferSize;
44          }
45  
46          @Override
47          public void record(int actualReadBytes) { }
48      }
49  
50      private final Handle handle;
51  
52      /**
53       * Creates a new predictor that always returns the same prediction of
54       * the specified buffer size.
55       */
56      public FixedRecvByteBufAllocator(int bufferSize) {
57          if (bufferSize <= 0) {
58              throw new IllegalArgumentException(
59                      "bufferSize must greater than 0: " + bufferSize);
60          }
61  
62          handle = new HandleImpl(bufferSize);
63      }
64  
65      @Override
66      public Handle newHandle() {
67          return handle;
68      }
69  }