bytebuf 是可以扩容的。
可扩容
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | package com.redisc;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufAllocator;
 import lombok.extern.slf4j.Slf4j;
 
 import java.io.IOException;
 
 
 @Slf4j
 public class Run {
 
 public static void main(String[] args) throws IOException {
 ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
 System.out.println(byteBuf);
 
 StringBuilder s = new StringBuilder();
 for (int i = 0; i < 300; i++) {
 s.append(i);
 }
 
 byteBuf.writeBytes(s.toString().getBytes());
 System.out.println(byteBuf);
 }
 
 }
 
 | 
输出
| 12
 
 | PooledUnsafeDirectByteBuf(ridx: 0, widx: 0, cap: 256)PooledUnsafeDirectByteBuf(ridx: 0, widx: 790, cap: 1024)
 
 | 
直接内存和堆内存
直接内存创建和销毁代价大,但是,读写效率高,适合配合池化一起用。
直接内存对 GC 压力小,因为垃圾不回收,但是要注意及时释放。
基于堆的池化
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.heapBuffer();
基于直接内存的池化
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.directBuffer(); 
池化 & 非池化
池化的最大意义可以重复使用 ByteBuf
- 没有池化,每次需要创建新的 ByteBuf的实例
- 有了池化,可以重用池中 ByteBuf的实例
- 高并发时,节约内存,减少溢出
netty4.1 之前池化并不成熟,4.1 之后默认是开启的。「Android 4.1 之后默认是关闭的」
关闭池化需要通过程序开启时传递参数做到,这里不再说明。