Nio-slice方法解决替代忘记写flip方法的作用

filp,slice,和duplicate

  • filp: 英文翻译为反转
  • slice: 切片

filp 用于切换 读写模式 . 创建Buffer时是写入模式,读取时需要切换才能进行读取. 切换时主要变更 Buffer的position和limit.

public class Test {
    public static void main(String[] args) {
        ByteBuffer allocate = ByteBuffer.allocate(16);
        allocate.putInt(1);
        allocate.flip();
        System.out.println(allocate.getInt());

    }
}

 

slice 创建一个Buffer , 共享 父Buffer 的内容, 在 slice 中的修改会直接反馈在 父Buffer中, Position,Limit,capacity 相互独立.

主要在不切换父Buffer时使用 , 在  RocketMq 中出现该使用方式
public class SliceTest {
    public static void main(String[] args) {
        ByteBuffer allocate = ByteBuffer.allocate(16);
        //切片1
        ByteBuffer slice = allocate.slice();
        slice.position(0);
        slice.putInt(1);
        //切片2
        ByteBuffer two = allocate.slice();
        two.position(4);
        two.putInt(2);
        System.out.println(allocate.getInt());//输出1
        System.out.println(allocate.getInt());//输出2
    }
}

 创建的ByteBuffer没有直接使用,而是通过共享的slice去进行修改,slice的修改会直接反馈在allocate的内容当中,省去了 filp . 避免了忘记 filp 的错误.

你可能感兴趣的:(NIO)