广东建设人才网站,反向代理wordpress,wordpress修改关键字,如何做招生网站Netty ByteBuf 分配
本文主要内容关于 ByteBuf 分配介绍#xff0c;为了更好的理解本文#xff0c;我们可以带着几个问题思考
在IO密集型业务场景下#xff0c;可能涉及大量ByteBuf分配#xff0c;这时我们需 要考虑会不会产生OOM会不会出现频繁GC会不会内存泄露
根据上…Netty ByteBuf 分配
本文主要内容关于 ByteBuf 分配介绍为了更好的理解本文我们可以带着几个问题思考
在IO密集型业务场景下可能涉及大量ByteBuf分配这时我们需 要考虑会不会产生OOM会不会出现频繁GC会不会内存泄露
根据上面的问题没准你也设计出netty的分配方案主要关键点
避免重复分配你也许会想到 线程池类似的复用技术解放GC你会如何绕过GC , 于是想到直接内存因为直接内存需要手动释放资源因此你需要考虑潜在的内存泄露问题
ByteBufAllocator ByteBufAllocator 是 Netty用于分配 ByteBuf 对象 的接口ByteBuf 分配方式主要有下面两个维度 在堆上分配还是使用直接内存 堆上分配受JVM 垃圾回收管理不需要手动释放资源。 直接内存不受JVM垃圾收集机制的管理需要手动释放资源在处理I/O操作时直接内存可以提高性能因为它减轻垃圾收集的压力 使用缓存池复用 和 不使用缓存池
池化技术我们平常接触的有数据库连接池、线程池等它避免资源重复创建和销毁带来的代价Netty 对象分配也支持用缓冲池复用。
ByteBufAllocator 分配方法介绍 buffer()
自动判断在堆上分配 or 直接内存上分配判断依据是否支持Unsafe ioBuffer() 尽可能在对直接内存上分配因为直接内存更适合用于IO如果不支持则在堆上分配。 heapBuffer()
在堆上分配受垃圾回收机制管理
directBuffer()
使用直接内存分配
CompositeByteBuf 分配
compositeBuffer()/compositeHeapBuffer()/compositeDirectBuffer()/ 用于CompositeByteBuf 分配
ByteBufAllocator 主要实现类
PooledByteBufAllocator
使用缓冲池技术通过重复利用已经分配的ByteBuf能够有效地减少内存分配和释放的开销。
UnpooledByteBufAllocator
它在每次分配ByteBuf时都会创建一个新的实例。
Unpooled
非池化分配也可以使用Unpooled 工具类,Unpooled 工具类其实调用UnpooledByteBufAllocator进行分配的,它提供了许多便捷的静态方法。 使用举例 import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;public class ByteBufAllocatorExample {public static void main(String[] args) {// 使用池化分配器ByteBufAllocator pooledAllocator PooledByteBufAllocator.DEFAULT;// 分配一个堆内存 ByteBufByteBuf heapBuf pooledAllocator.heapBuffer(1024);heapBuf.writeBytes(Hello, Heap Buffer!.getBytes());System.out.println(Heap Buffer: heapBuf.toString(io.netty.util.CharsetUtil.UTF_8));heapBuf.release();// 分配一个直接内存 ByteBufByteBuf directBuf pooledAllocator.directBuffer(1024);directBuf.writeBytes(Hello, Direct Buffer!.getBytes());System.out.println(Direct Buffer: directBuf.toString(io.netty.util.CharsetUtil.UTF_8));directBuf.release();// 使用非池化分配器ByteBufAllocator unpooledAllocator UnpooledByteBufAllocator.DEFAULT;// 分配一个堆内存 ByteBufByteBuf heapBufUnpooled unpooledAllocator.heapBuffer(1024);heapBufUnpooled.writeBytes(Hello, Unpooled Heap Buffer!.getBytes());System.out.println(Unpooled Heap Buffer: heapBufUnpooled.toString(io.netty.util.CharsetUtil.UTF_8));heapBufUnpooled.release();// 分配一个直接内存 ByteBufByteBuf directBufUnpooled unpooledAllocator.directBuffer(1024);directBufUnpooled.writeBytes(Hello, Unpooled Direct Buffer!.getBytes());System.out.println(Unpooled Direct Buffer: directBufUnpooled.toString(io.netty.util.CharsetUtil.UTF_8));directBufUnpooled.release();ByteBuf unpooledBuffer Unpooled.buffer(1024);}
}总结
要不要使用缓冲池使用直接内存还是Java堆都要看具体业务在IO场景Netty 内部优先使用直接内存频繁的IO操作推荐使用缓冲池分配避免内存频繁创建和销毁带来的开销。