javaNio DirectByteBuffer常用方法解析

一,简介

  

DirectByteBuffer是ByteBuffer关于堆外内存使用的实现,堆外内存直接使用unsafe方法请求堆外内存空间,读写数据,直接使用内存地址,效率非常的高

使用ByteBuffer提供的工厂类可获得实例:
  
ByteBuffer sendBuf1 = ByteBuffer.allocateDirect(10);


1,常用类putInt
sendBuf1.putInt(1);

此方法使用4个字节保存int类型的数据


实现方法:
    public ByteBuffer putInt(int x) {

        putInt(ix(nextPutIndex((1 << 2))), x);
        return this;

    }
nextPutIndex 写入数据时通过position 计算下一个写入的数据事第几个
    final int nextPutIndex(int nb) {                    // package-private
        if (limit - position < nb)
            throw new BufferOverflowException();
        int p = position;
        position += nb;
        return p;
    }
ix 方法计算下一个数据写入的内存地址
address 在创建实例时,申请内存地址后保存的,申请到内存地址的首地址address+position+1便是下一个可写入地址
    private long ix(int i) {
        return address + ((long)i << 0);
    }
unaligned :判断系统架构
 如果是以下架构便返回ture

nativeByteOrder :判断系统储存使用的是大端还是小端,如果系统是大端返回true

 关于大端小端的详细介绍:https://www.cnblogs.com/dybe/p/11790955.html

Bits.swap(y) :小端情况下,将int类型的字节顺序反转后得到的补码值

unsafe.putInt(long a,int b)
unsafe提供的直接操作内存的方法,a:内存地址,b:要写入的数据
Bits.putInt 自己实现数据字节翻转保存
 
    
//a:写入数据的内存地址
//x:要写入的数据
private ByteBuffer putInt(long a, int x) { if (unaligned) { int y = (x); unsafe.putInt(a, (nativeByteOrder ? y : Bits.swap(y))); } else { Bits.putInt(a, x, bigEndian); } return this; }

 2,getInt方法同理如果是小端,将数据取出后,进行字节反转后再返回

    private int getInt(long a) {
        if (unaligned) {
            int x = unsafe.getInt(a);
            return (nativeByteOrder ? x : Bits.swap(x));
        }
        return Bits.getInt(a, bigEndian);
    }

猜你喜欢

转载自www.cnblogs.com/dybe/p/11790887.html