+--------+-------------------- all ------------------------+----------------+ position: [1], limit: [10] +-------------------------------------------------+ | 0123456789 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 61000000000000000000 |a......... | +--------+-------------------------------------------------+----------------+ +--------+-------------------- all ------------------------+----------------+ position: [3], limit: [10] +-------------------------------------------------+ | 0123456789 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 61626300000000000000 |abc....... | +--------+-------------------------------------------------+----------------+ 97 +--------+-------------------- all ------------------------+----------------+ position: [1], limit: [3] +-------------------------------------------------+ | 0123456789 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 61626300000000000000 |abc....... | +--------+-------------------------------------------------+----------------+ +--------+-------------------- all ------------------------+----------------+ position: [2], limit: [10] +-------------------------------------------------+ | 0123456789 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 62636300000000000000 |bcc....... | +--------+-------------------------------------------------+----------------+ +--------+-------------------- all ------------------------+----------------+ position: [3], limit: [10] +-------------------------------------------------+ | 0123456789 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 62636500000000000000 |bce....... | +--------+-------------------------------------------------+----------------+
分配内存
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package com.redisc;
import lombok.extern.slf4j.Slf4j;
import java.nio.ByteBuffer;
@Slf4j(topic = "c.Test") public class Run {
public static void main(String[] args) { System.out.println(ByteBuffer.allocate(16).getClass()); System.out.println(ByteBuffer.allocateDirect(16).getClass()); } }
输出
1 2
class java.nio.HeapByteBuffer --java 堆内存,读写效率低,垃圾可以回收 class java.nio.DirectByteBuffer -- 直接内存,读写效率高,垃圾不回收,分配的效率低
//从头读 buffer.get(newbyte[4]); // 会移动 position abcd buffer.rewind(); //再次把 position 指向 0,又可以重新读取了 buffer.get(); // a position 指向 1 buffer.mark(); // 做标记,记录一下 position 位置,mark = 1 buffer.get(); // b position 指向 2 buffer.reset(); // 将 position 重制到 mark 位置 position = 1 System.out.println((char)buffer.get()); // b buffer.get(3); // d 但是 position 不会变 get(i) 不改变读索引的位置