美文网首页
AdaptiveRecvByteBufAllocator类详解

AdaptiveRecvByteBufAllocator类详解

作者: 蜡笔没了小新_e8c0 | 来源:发表于2019-12-06 20:58 被阅读0次

    1 介绍

    /**
     * The {@link RecvByteBufAllocator} that automatically increases and
     * decreases the predicted buffer size on feed back.
     * <p>
     * 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<Integer> sizeTable = new ArrayList<Integer>();
            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类详解

          本文链接:https://www.haomeiwen.com/subject/mbzegctx.html