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,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);
         }
         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.反序列化就出问题了。

你可能感兴趣的:(Droid,OpenAtlas)