AdaptiveRecvByteBufAllocator类详解

1 介绍

/**
 * The {@link RecvByteBufAllocator} that automatically increases and
 * decreases the predicted buffer size on feed back.
 * 

* It gradually increases the expected number of readable bytes if the previous * read fully filled the allocated buffer. It gradually decreases the expected * number of readable bytes if the read operation was not able to fill a certain * amount of the allocated buffer two times consecutively. Otherwise, it keeps * returning the same prediction. */

用来自动增加或减少可预测的buffer的大小。
当上一次read操作填满了所有的可分配的buffer空间,就会按照期望的增加可读字节数;当之前连续的两次read操作都不能填充一点数量的内容,就会对减少可读的字节数目。

2 属性说明

    //最小值
    static final int DEFAULT_MINIMUM = 64;
    //默认值
    static final int DEFAULT_INITIAL = 1024;
    //最大值
    static final int DEFAULT_MAXIMUM = 65536;
   
    //数组索引增加的步长
    private static final int INDEX_INCREMENT = 4;
    //数组索引减少的步长
    private static final int INDEX_DECREMENT = 1;

    //存放所有大小值的数组
    private static final int[] SIZE_TABLE;

3 初始化SIZE_TABLE数组

    static {
        List sizeTable = new ArrayList();
        for (int i = 16; i < 512; i += 16) {
            sizeTable.add(i);
        }

        for (int i = 512; i > 0; i <<= 1) {
            sizeTable.add(i);
        }

        SIZE_TABLE = new int[sizeTable.size()];
        for (int i = 0; i < SIZE_TABLE.length; i ++) {
            SIZE_TABLE[i] = sizeTable.get(i);
        }
    }

SIZE_TABLE可以分为两部分值,前31个元素从16开始,以16的步长递增;其余的元素从512开始每次扩大一倍,知道Intger的最大值。

4 getSizeTableIndex方法

    private static int getSizeTableIndex(final int size) {
        for (int low = 0, high = SIZE_TABLE.length - 1;;) {
            if (high < low) {
                return low;
            }
            if (high == low) {
                return high;
            }

            int mid = low + high >>> 1;
            int a = SIZE_TABLE[mid];
            int b = SIZE_TABLE[mid + 1];
            if (size > b) {
                low = mid + 1;
            } else if (size < a) {
                high = mid - 1;
            } else if (size == a) {
                return mid;
            } else {
                return mid + 1;
            }
        }
    }

你可能感兴趣的:(AdaptiveRecvByteBufAllocator类详解)