Android-那些年我们进过的坑-ByteBuffer导致的bug

Android-那些年我们进过的坑-ByteBuffer导致的bug

前几天发现这么一个问题,自己实现的序列化,按字节操作。5.0一直没测试,发现反序列化有问题,一直以为数据库的问题。折腾了一晚上。
都知道在5.0 google做了好多优化。

我们使用了allocateDirect,debug发现5.0上出问题的时候offset不是0,而5.0一下的时候offset都是0

4.4中的源码

DirectByteBuffer第三个参数是offset,4.4一下是写死的
/**
     * Creates a direct byte buffer based on a newly allocated memory block.
     *
     * @param capacity
     *            the capacity of the new buffer
     * @return the created byte buffer.
     * @throws IllegalArgumentException
     *             if {@code capacity < 0}.
     */
    public static ByteBuffer allocateDirect(int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException("capacity < 0: " + capacity);
        }
        return new DirectByteBuffer(MemoryBlock.allocate(capacity), capacity, 0, false, null);
    }



5.0的源码这样子

/**
      * Creates a direct byte buffer based on a newly allocated memory block.
      *
      * @param capacity
      *            the capacity of the new buffer
      * @return the created byte buffer.
      * @throws IllegalArgumentException
      *             if {@code capacity < 0}.
      */
     public static ByteBuffer allocateDirect(int capacity) {
         if (capacity < 0) {
             throw new IllegalArgumentException("capacity < 0: " + capacity);
         }
         // Ensure alignment by 8.
         MemoryBlock memoryBlock = MemoryBlock.allocate(capacity + 7);
         long address = memoryBlock.toLong();
         long alignedAddress = (address + 7) & ~(long)7;
         return new DirectByteBuffer(memoryBlock, capacity, (int)(alignedAddress - address), false, null);
     }





 

在5.0后 做了内存对齐alignedAddress - address,直接读取的字节array还是从地址最开始,导致读取了一堆0.反序列化就出问题了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值