//这里的1024 表示缓冲区的容量
ByteBuffer allocate = ByteBuffer.allocate(1024);
allocate.putLong(1);
allocate.putInt(2);
allocate.putDouble(1.2);
allocate.flip(); //将缓存区界限设置为当前位置,并将当前位置重置为0,相当于切换成了读模式
//这里可以想象成了一个解包的过程,我们必须按照加入的顺序读取类型,否则会导致数据不一致
long aLong = allocate.getLong();
System.out.println(aLong);
allocate.mark();//创建一个position标记
long aLong = allocate.getLong();
int anInt = allocate.getInt();
System.out.println(aLong);
System.out.println(anInt);
allocate.reset(); //恢复到标记处的position
long aLong1 = allocate.getLong();
System.out.println(aLong1);
ByteBuffer bytebuffer = ByteBuffer.allocateDirect(1024);
优点 可以减少一次拷贝,提供访问速度
缺点 不好把握,容易内存泄露
直接内存什么时候释放
该块内存不受jvm管理,内部使用了unsafe开辟与回收,当bytebuffer 实例需要被gc回收,会调用unsafe.freeMemory() 释放内存,所以不使用了我们直接bytebuffer=null; 就可以回收掉
LongBuffer
IntBuffer
除可boolean 没有基本类型都有对应的方法