netty 内存操作
内存分类
netty可使用堆内存、直接内存(堆外内存),并可使用缓冲池进行内存复用
UnpooledHeapByteBuf:非池化堆内存 UnpooledUnsafeHeapByteBuf:非池化的unsafe堆内存 UnpooledDirectByteBuf:非池化的直接内存(堆外内存) UnpooledUnsafeDirectteBuf:非池化的unsafe直接内存(堆外内存) PooledHeapByteBuf:池化堆内存 PooledUnsafeHeapByteBuf:池化的unsafe堆内存 PooledDirectByteBuf:池化的直接内存(堆外内存) PooledUnsafeDirectteBuf:池化的unsafe直接内存(堆外内存)
ByteBuf
public abstract class ByteBuf implements ReferenceCounted, Comparable, ByteBufConvertible { public ByteBuf() { } ******* get操作:不会修改读指针 public abstract byte getByte(int var1); public abstract char getChar(int var1); public abstract boolean getBoolean(int var1); public abstract short getUnsignedByte(int var1); public abstract short getShort(int var1); public abstract short getShortLE(int var1); public abstract int getUnsignedShort(int var1); public abstract int getUnsignedShortLE(int var1); public abstract int getMedium(int var1); public abstract int getMediumLE(int var1); public abstract int getUnsignedMedium(int var1); public abstract int getUnsignedMediumLE(int var1); public abstract int getInt(int var1); public abstract int getIntLE(int var1); public abstract long getUnsignedInt(int var1); public abstract long getUnsignedIntLE(int var1); public abstract long getLong(int var1); public abstract long getLongLE(int var1); public abstract float getFloat(int var1); public float getFloatLE(int index) { public abstract double getDouble(int var1); public double getDoubleLE(int index) { public abstract ByteBuf getBytes(int var1, ByteBuf var2); public abstract ByteBuf getBytes(int var1, ByteBuf var2, int var3); public abstract ByteBuf getBytes(int var1, ByteBuf var2, int var3, int var4); public abstract ByteBuf getBytes(int var1, byte[] var2); public abstract ByteBuf getBytes(int var1, byte[] var2, int var3, int var4); public abstract ByteBuf getBytes(int var1, ByteBuffer var2); public abstract ByteBuf getBytes(int var1, OutputStream var2, int var3) throws IOException; public abstract int getBytes(int var1, GatheringByteChannel var2, int var3) throws IOException; public abstract int getBytes(int var1, FileChannel var2, long var3, int var5) throws IOException; public abstract CharSequence getCharSequence(int var1, int var2, Charset var3); ******* set操作:不会修改写指针 public abstract ByteBuf setByte(int var1, int var2); public abstract ByteBuf setChar(int var1, int var2); public abstract ByteBuf setZero(int var1, int var2); public abstract ByteBuf setBoolean(int var1, boolean var2); public abstract ByteBuf setShort(int var1, int var2); public abstract ByteBuf setShortLE(int var1, int var2); public abstract ByteBuf setMedium(int var1, int var2); public abstract ByteBuf setMediumLE(int var1, int var2); public abstract ByteBuf setInt(int var1, int var2); public abstract ByteBuf setIntLE(int var1, int var2); public abstract ByteBuf setLong(int var1, long var2); public abstract ByteBuf setLongLE(int var1, long var2); public abstract ByteBuf setFloat(int var1, float var2); public ByteBuf setFloatLE(int index, float value) { public abstract ByteBuf setDouble(int var1, double var2); public ByteBuf setDoubleLE(int index, double value) { public abstract ByteBuf setBytes(int var1, ByteBuf var2); public abstract ByteBuf setBytes(int var1, ByteBuf var2, int var3); public abstract ByteBuf setBytes(int var1, ByteBuf var2, int var3, int var4); public abstract ByteBuf setBytes(int var1, byte[] var2); public abstract ByteBuf setBytes(int var1, byte[] var2, int var3, int var4); public abstract ByteBuf setBytes(int var1, ByteBuffer var2); public abstract int setBytes(int var1, InputStream var2, int var3) throws IOException; public abstract int setBytes(int var1, ScatteringByteChannel var2, int var3) throws IOException; public abstract int setBytes(int var1, FileChannel var2, long var3, int var5) throws IOException; public abstract int setCharSequence(int var1, CharSequence var2, Charset var3); ******* read操作:会修改读指针 public abstract byte readByte(); public abstract char readChar(); public abstract boolean readBoolean(); public abstract short readShort(); public abstract short readShortLE(); public abstract short readUnsignedByte(); public abstract int readUnsignedShort(); public abstract int readUnsignedShortLE(); public abstract int readMedium(); public abstract int readMediumLE(); public abstract int readUnsignedMedium(); public abstract int readUnsignedMediumLE(); public abstract int readInt(); public abstract int readIntLE(); public abstract long readUnsignedInt(); public abstract long readUnsignedIntLE(); public abstract long readLong(); public abstract long readLongLE(); public abstract float readFloat(); public float readFloatLE() { public abstract double readDouble(); public double readDoubleLE() { public abstract ByteBuf readSlice(int var1); public abstract ByteBuf readRetainedSlice(int var1); public abstract ByteBuf readBytes(int var1); public abstract ByteBuf readBytes(ByteBuf var1); public abstract ByteBuf readBytes(ByteBuf var1, int var2); public abstract ByteBuf readBytes(ByteBuf var1, int var2, int var3); public abstract ByteBuf readBytes(byte[] var1); public abstract ByteBuf readBytes(byte[] var1, int var2, int var3); public abstract ByteBuf readBytes(ByteBuffer var1); public abstract ByteBuf readBytes(OutputStream var1, int var2) throws IOException; public abstract int readBytes(GatheringByteChannel var1, int var2) throws IOException; public abstract int readBytes(FileChannel var1, long var2, int var4) throws IOException; public abstract CharSequence readCharSequence(int var1, Charset var2); ******* write操作:会修改写指针 public abstract ByteBuf writeByte(int var1); public abstract ByteBuf writeChar(int var1); public abstract ByteBuf writeZero(int var1); public abstract ByteBuf writeBoolean(boolean var1); public abstract ByteBuf writeShort(int var1); public abstract ByteBuf writeShortLE(int var1); public abstract ByteBuf writeMedium(int var1); public abstract ByteBuf writeMediumLE(int var1); public abstract ByteBuf writeInt(int var1); public abstract ByteBuf writeIntLE(int var1); public abstract ByteBuf writeLong(long var1); public abstract ByteBuf writeLongLE(long var1); public abstract ByteBuf writeFloat(float var1); public abstract ByteBuf writeDouble(double var1); public ByteBuf writeFloatLE(float value) { public ByteBuf writeDoubleLE(double value) { public abstract ByteBuf writeBytes(ByteBuf var1); public abstract ByteBuf writeBytes(ByteBuf var1, int var2); public abstract ByteBuf writeBytes(ByteBuf var1, int var2, int var3); public abstract ByteBuf writeBytes(byte[] var1); public abstract ByteBuf writeBytes(byte[] var1, int var2, int var3); public abstract ByteBuf writeBytes(ByteBuffer var1); public abstract int writeBytes(InputStream var1, int var2) throws IOException; public abstract int writeBytes(ScatteringByteChannel var1, int var2) throws IOException; public abstract int writeBytes(FileChannel var1, long var2, int var4) throws IOException; public abstract int writeCharSequence(CharSequence var1, Charset var2); ******* 读写index public abstract int readerIndex(); public abstract int writerIndex(); public abstract ByteBuf readerIndex(int var1); public abstract ByteBuf writerIndex(int var1); public abstract ByteBuf markReaderIndex(); public abstract ByteBuf resetReaderIndex(); public abstract ByteBuf markWriterIndex(); public abstract ByteBuf resetWriterIndex(); public abstract ByteBuf setIndex(int var1, int var2); public abstract boolean isReadable(); public abstract boolean isReadable(int var1); public abstract boolean isWritable(); public abstract boolean isWritable(int var1); public abstract int readableBytes(); public abstract int writableBytes(); public abstract int maxWritableBytes(); public int maxFastWritableBytes() { public abstract ByteBuf ensureWritable(int var1); public abstract int ensureWritable(int var1, boolean var2); public abstract ByteBuf discardReadBytes(); public abstract ByteBuf discardSomeReadBytes(); ******* 其余操作 public abstract int capacity(); public abstract int maxCapacity(); public abstract ByteBuf capacity(int var1); public abstract ByteBufAllocator alloc(); public abstract ByteBuf unwrap(); public abstract ByteBuf asReadOnly(); public abstract boolean isDirect(); public abstract boolean isReadOnly(); public abstract int bytesBefore(byte var1); public abstract int bytesBefore(int var1, byte var2); public abstract int bytesBefore(int var1, int var2, byte var3); public abstract int forEachByte(ByteProcessor var1); public abstract int forEachByte(int var1, int var2, ByteProcessor var3); public abstract int forEachByteDesc(ByteProcessor var1); public abstract int forEachByteDesc(int var1, int var2, ByteProcessor var3); public abstract int nioBufferCount(); public abstract ByteBuffer nioBuffer(); public abstract ByteBuffer nioBuffer(int var1, int var2); public abstract ByteBuffer internalNioBuffer(int var1, int var2); public abstract ByteBuffer[] nioBuffers(); public abstract ByteBuffer[] nioBuffers(int var1, int var2); public abstract ByteBuf clear(); public abstract ByteBuf skipBytes(int var1); public abstract int indexOf(int var1, int var2, byte var3); public abstract boolean hasArray(); //堆内存返回true,直接内存返回false public abstract byte[] array(); //堆内存中连续的数组 public abstract int arrayOffset(); public abstract boolean hasMemoryAddress(); //堆内存返回false,直接内存返回true public abstract long memoryAddress(); //直接内存的内存地址 public abstract ByteBuf copy(); public abstract ByteBuf copy(int var1, int var2); public abstract ByteBuf slice(); public abstract ByteBuf slice(int var1, int var2); public abstract ByteBuf retainedSlice(); public abstract ByteBuf retainedSlice(int var1, int var2); public abstract ByteBuf duplicate(); public abstract ByteBuf retainedDuplicate(); public abstract ByteBuf retain(); public abstract ByteBuf retain(int var1); public abstract ByteBuf touch(); public abstract ByteBuf touch(Object var1); public boolean isContiguous() { return false; } public ByteBuf asByteBuf() { return this; } public abstract int hashCode(); public abstract boolean equals(Object var1); public abstract String toString(); public abstract String toString(Charset var1); public abstract String toString(int var1, int var2, Charset var3); public abstract int compareTo(ByteBuf var1); boolean isAccessible() { return this.refCnt() != 0; } }
内存分配器
ByteBufAllocator:内存分配器
public interface ByteBufAllocator {
ByteBufAllocator DEFAULT = ByteBufUtil.DEFAULT_ALLOCATOR;
ByteBuf buffer(); //自动判断分配直接内存或者堆内存(优先直接内存)
ByteBuf buffer(int var1);
ByteBuf buffer(int var1, int var2);
ByteBuf ioBuffer(); //尽量分配直接内存,如果系统不支持则分配堆内存
ByteBuf ioBuffer(int var1);
ByteBuf ioBuffer(int var1, int var2);
ByteBuf heapBuffer(); //分配堆内存
ByteBuf heapBuffer(int var1);
ByteBuf heapBuffer(int var1, int var2);
ByteBuf directBuffer(); //分配直接内存
ByteBuf directBuffer(int var1);
ByteBuf directBuffer(int var1, int var2);
CompositeByteBuf compositeBuffer(); //组合内存
CompositeByteBuf compositeBuffer(int var1);
CompositeByteBuf compositeHeapBuffer(); //组合堆内存
CompositeByteBuf compositeHeapBuffer(int var1);
CompositeByteBuf compositeDirectBuffer(); //组合直接内存
CompositeByteBuf compositeDirectBuffer(int var1);
boolean isDirectBufferPooled();
int calculateNewCapacity(int var1, int var2);
}
AbstractByteBufAllocator
public abstract class AbstractByteBufAllocator implements ByteBufAllocator {
static final int DEFAULT_INITIAL_CAPACITY = 256;
static final int DEFAULT_MAX_CAPACITY = 2147483647;
static final int DEFAULT_MAX_COMPONENTS = 16;
static final int CALCULATE_THRESHOLD = 4194304;
private final boolean directByDefault;
private final ByteBuf emptyBuf;
*********
buffer:默认分配直接内存(可通过参数设置)
public ByteBuf buffer() {
return this.directByDefault ? this.directBuffer() : this.heapBuffer();
}
public ByteBuf buffer(int initialCapacity) {
return this.directByDefault ? this.directBuffer(initialCapacity) : this.heapBuffer(initialCapacity);
}
public ByteBuf buffer(int initialCapacity, int maxCapacity) {
return this.directByDefault ? this.directBuffer(initialCapacity, maxCapacity) : this.heapBuffer(initialCapacity, maxCapacity);
}
*********
ioBuffer:优先分配直接内存
public ByteBuf ioBuffer() {
return !PlatformDependent.hasUnsafe() && !this.isDirectBufferPooled() ? this.heapBuffer(256) : this.directBuffer(256);
}
public ByteBuf ioBuffer(int initialCapacity) {
return !PlatformDependent.hasUnsafe() && !this.isDirectBufferPooled() ? this.heapBuffer(initialCapacity) : this.directBuffer(initialCapacity);
}
public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) {
return !PlatformDependent.hasUnsafe() && !this.isDirectBufferPooled() ? this.heapBuffer(initialCapacity, maxCapacity) : this.directBuffer(initialCapacity, maxCapacity);
}
*********
heapBuffer:分配堆内存
public ByteBuf heapBuffer() {
return this.heapBuffer(256, 2147483647);
}
public ByteBuf heapBuffer(int initialCapacity) {
return this.heapBuffer(initialCapacity, 2147483647);
}
public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) {
if (initialCapacity == 0 && maxCapacity == 0) {
return this.emptyBuf;
} else {
validate(initialCapacity, maxCapacity);
return this.newHeapBuffer(initialCapacity, maxCapacity);
}
}
*********
directBuffer:分配直接内存
public ByteBuf directBuffer() {
return this.directBuffer(256, 2147483647);
}
public ByteBuf directBuffer(int initialCapacity) {
return this.directBuffer(initialCapacity, 2147483647);
}
public ByteBuf directBuffer(int initialCapacity, int maxCapacity) {
if (initialCapacity == 0 && maxCapacity == 0) {
return this.emptyBuf;
} else {
validate(initialCapacity, maxCapacity);
return this.newDirectBuffer(initialCapacity, maxCapacity);
}
}
*********
compositeBuffer:分配组合内存
public CompositeByteBuf compositeBuffer() { //默认优先分配组合直接内存
return this.directByDefault ? this.compositeDirectBuffer() : this.compositeHeapBuffer();
}
public CompositeByteBuf compositeBuffer(int maxNumComponents) {
return this.directByDefault ? this.compositeDirectBuffer(maxNumComponents) : this.compositeHeapBuffer(maxNumComponents);
}
public CompositeByteBuf compositeHeapBuffer() { //组合堆内存
return this.compositeHeapBuffer(16);
}
public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) {
return toLeakAwareBuffer(new CompositeByteBuf(this, false, maxNumComponents));
}
public CompositeByteBuf compositeDirectBuffer() { //组合直接内存
return this.compositeDirectBuffer(16);
}
public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) {
return toLeakAwareBuffer(new CompositeByteBuf(this, true, maxNumComponents));
}
*********
其他方法
public int calculateNewCapacity(int minNewCapacity, int maxCapacity) {
public String toString() {
protected abstract ByteBuf newHeapBuffer(int var1, int var2);
protected abstract ByteBuf newDirectBuffer(int var1, int var2);
protected static ByteBuf toLeakAwareBuffer(ByteBuf buf) {
protected static CompositeByteBuf toLeakAwareBuffer(CompositeByteBuf buf) {
protected AbstractByteBufAllocator() {
protected AbstractByteBufAllocator(boolean preferDirect) {
private static void validate(int initialCapacity, int maxCapacity) {
static {
ResourceLeakDetector.addExclusions(AbstractByteBufAllocator.class, new String[]{"toLeakAwareBuffer"});
}
}
PooledByteBufAllocator:池化内存分配器
public class PooledByteBufAllocator extends AbstractByteBufAllocator implements ByteBufAllocatorMetricProvider {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(PooledByteBufAllocator.class);
private static final int DEFAULT_NUM_HEAP_ARENA;
private static final int DEFAULT_NUM_DIRECT_ARENA;
private static final int DEFAULT_PAGE_SIZE;
private static final int DEFAULT_MAX_ORDER;
private static final int DEFAULT_SMALL_CACHE_SIZE;
private static final int DEFAULT_NORMAL_CACHE_SIZE;
static final int DEFAULT_MAX_CACHED_BUFFER_CAPACITY;
private static final int DEFAULT_CACHE_TRIM_INTERVAL;
private static final long DEFAULT_CACHE_TRIM_INTERVAL_MILLIS;
private static final boolean DEFAULT_USE_CACHE_FOR_ALL_THREADS;
private static final int DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT;
static final int DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK;
private static final int MIN_PAGE_SIZE = 4096;
private static final int MAX_CHUNK_SIZE = 1073741824;
private static final int CACHE_NOT_USED = 0;
private final Runnable trimTask;
public static final PooledByteBufAllocator DEFAULT;
private final PoolArena[] heapArenas;
private final PoolArena[] directArenas;
private final int smallCacheSize;
private final int normalCacheSize;
private final List heapArenaMetrics;
private final List directArenaMetrics;
private final PooledByteBufAllocator.PoolThreadLocalCache threadCache;
private final int chunkSize;
private final PooledByteBufAllocatorMetric metric;
public PooledByteBufAllocator() {
public PooledByteBufAllocator(boolean preferDirect) {
public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder) {
public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder, int smallCacheSize, int normalCacheSize, boolean useCacheForAllThreads) {
public PooledByteBufAllocator(boolean preferDirect, int nHeapArena, int nDirectArena, int pageSize, int maxOrder, int smallCacheSize, int normalCacheSize, boolean useCacheForAllThreads, int directMemoryCacheAlignment) {
public static int defaultPageSize() {
public static int defaultMaxOrder() {
public static int defaultNumHeapArena() {
public static int defaultNumDirectArena() {
public static int defaultSmallCacheSize() {
public static int defaultNormalCacheSize() {
public static boolean defaultPreferDirect() {
public static boolean defaultUseCacheForAllThreads() {
public static boolean isDirectMemoryCacheAlignmentSupported() {
public boolean trimCurrentThreadCache() {
public boolean isDirectBufferPooled() {
public PooledByteBufAllocatorMetric metric() {
public String dumpStats() {
public final long pinnedHeapMemory() {
public final long pinnedDirectMemory() {
final long usedHeapMemory() {
final long usedDirectMemory() {
final PoolThreadCache threadCache() {
protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
private static long usedMemory(PoolArena>[] arenas) {
private static long pinnedMemory(PoolArena>[] arenas) {
private static PoolArena[] newArenaArray(int size) {
private static int validateAndCalculateChunkSize(int pageSize, int maxOrder) {
private static int validateAndCalculatePageShifts(int pageSize, int alignment) {
static {
int defaultAlignment = SystemPropertyUtil.getInt("io.netty.allocator.directMemoryCacheAlignment", 0);
int defaultPageSize = SystemPropertyUtil.getInt("io.netty.allocator.pageSize", 8192);
Throwable pageSizeFallbackCause = null;
try {
validateAndCalculatePageShifts(defaultPageSize, defaultAlignment);
} catch (Throwable var9) {
pageSizeFallbackCause = var9;
defaultPageSize = 8192;
defaultAlignment = 0;
}
DEFAULT_PAGE_SIZE = defaultPageSize;
DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT = defaultAlignment;
int defaultMaxOrder = SystemPropertyUtil.getInt("io.netty.allocator.maxOrder", 9);
Throwable maxOrderFallbackCause = null;
try {
validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder);
} catch (Throwable var8) {
maxOrderFallbackCause = var8;
defaultMaxOrder = 11;
}
DEFAULT_MAX_ORDER = defaultMaxOrder;
Runtime runtime = Runtime.getRuntime();
int defaultMinNumArena = NettyRuntime.availableProcessors() * 2;
int defaultChunkSize = DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER;
DEFAULT_NUM_HEAP_ARENA = Math.max(0, SystemPropertyUtil.getInt("io.netty.allocator.numHeapArenas", (int)Math.min((long)defaultMinNumArena, runtime.maxMemory() / (long)defaultChunkSize / 2L / 3L)));
DEFAULT_NUM_DIRECT_ARENA = Math.max(0, SystemPropertyUtil.getInt("io.netty.allocator.numDirectArenas", (int)Math.min((long)defaultMinNumArena, PlatformDependent.maxDirectMemory() / (long)defaultChunkSize / 2L / 3L)));
DEFAULT_SMALL_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.smallCacheSize", 256);
DEFAULT_NORMAL_CACHE_SIZE = SystemPropertyUtil.getInt("io.netty.allocator.normalCacheSize", 64);
DEFAULT_MAX_CACHED_BUFFER_CAPACITY = SystemPropertyUtil.getInt("io.netty.allocator.maxCachedBufferCapacity", 32768);
DEFAULT_CACHE_TRIM_INTERVAL = SystemPropertyUtil.getInt("io.netty.allocator.cacheTrimInterval", 8192);
if (SystemPropertyUtil.contains("io.netty.allocation.cacheTrimIntervalMillis")) {
logger.warn("-Dio.netty.allocation.cacheTrimIntervalMillis is deprecated, use -Dio.netty.allocator.cacheTrimIntervalMillis");
if (SystemPropertyUtil.contains("io.netty.allocator.cacheTrimIntervalMillis")) {
DEFAULT_CACHE_TRIM_INTERVAL_MILLIS = SystemPropertyUtil.getLong("io.netty.allocator.cacheTrimIntervalMillis", 0L);
} else {
DEFAULT_CACHE_TRIM_INTERVAL_MILLIS = SystemPropertyUtil.getLong("io.netty.allocation.cacheTrimIntervalMillis", 0L);
}
} else {
DEFAULT_CACHE_TRIM_INTERVAL_MILLIS = SystemPropertyUtil.getLong("io.netty.allocator.cacheTrimIntervalMillis", 0L);
}
DEFAULT_USE_CACHE_FOR_ALL_THREADS = SystemPropertyUtil.getBoolean("io.netty.allocator.useCacheForAllThreads", false);
DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK = SystemPropertyUtil.getInt("io.netty.allocator.maxCachedByteBuffersPerChunk", 1023);
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA);
logger.debug("-Dio.netty.allocator.numDirectArenas: {}", DEFAULT_NUM_DIRECT_ARENA);
if (pageSizeFallbackCause == null) {
logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE);
} else {
logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause);
}
if (maxOrderFallbackCause == null) {
logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER);
} else {
logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause);
}
logger.debug("-Dio.netty.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER);
logger.debug("-Dio.netty.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE);
logger.debug("-Dio.netty.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE);
logger.debug("-Dio.netty.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY);
logger.debug("-Dio.netty.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL);
logger.debug("-Dio.netty.allocator.cacheTrimIntervalMillis: {}", DEFAULT_CACHE_TRIM_INTERVAL_MILLIS);
logger.debug("-Dio.netty.allocator.useCacheForAllThreads: {}", DEFAULT_USE_CACHE_FOR_ALL_THREADS);
logger.debug("-Dio.netty.allocator.maxCachedByteBuffersPerChunk: {}", DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK);
}
DEFAULT = new PooledByteBufAllocator(PlatformDependent.directBufferPreferred());
//default设置为池化内存分配器
}
**********
内部类:PoolThreadLocalCache
private final class PoolThreadLocalCache extends FastThreadLocal {
private final boolean useCacheForAllThreads;
PoolThreadLocalCache(boolean useCacheForAllThreads) {
protected synchronized PoolThreadCache initialValue() {
protected void onRemoval(PoolThreadCache threadCache) {
private PoolArena leastUsedArena(PoolArena[] arenas) {
UnpooledByteBufAllocator:非池化内存分配器
public final class UnpooledByteBufAllocator extends AbstractByteBufAllocator implements ByteBufAllocatorMetricProvider {
private final UnpooledByteBufAllocator.UnpooledByteBufAllocatorMetric metric;
private final boolean disableLeakDetector;
private final boolean noCleaner;
public static final UnpooledByteBufAllocator DEFAULT = new UnpooledByteBufAllocator(PlatformDependent.directBufferPreferred());
public UnpooledByteBufAllocator(boolean preferDirect) {
public UnpooledByteBufAllocator(boolean preferDirect, boolean disableLeakDetector) {
public UnpooledByteBufAllocator(boolean preferDirect, boolean disableLeakDetector, boolean tryNoCleaner) {
public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) {
public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) {
public boolean isDirectBufferPooled() {
public ByteBufAllocatorMetric metric() {
void incrementDirect(int amount) {
void decrementDirect(int amount) {
void incrementHeap(int amount) {
void decrementHeap(int amount) {
protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
*********
内部类:UnpooledByteBufAllocatorMetric
private static final class UnpooledByteBufAllocatorMetric implements ByteBufAllocatorMetric {
final LongCounter directCounter;
final LongCounter heapCounter;
private UnpooledByteBufAllocatorMetric() {
public long usedHeapMemory() {
public long usedDirectMemory() {
public String toString() {
*********
内部类:InstrumentedUnpooledDirectByteBuf
private static final class InstrumentedUnpooledDirectByteBuf extends UnpooledDirectByteBuf {
InstrumentedUnpooledDirectByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
super(alloc, initialCapacity, maxCapacity);
}
protected ByteBuffer allocateDirect(int initialCapacity) {
protected void freeDirect(ByteBuffer buffer) {
*********
内部类:InstrumentedUnpooledUnsafeDirectByteBuf
private static final class InstrumentedUnpooledUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf {
InstrumentedUnpooledUnsafeDirectByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
super(alloc, initialCapacity, maxCapacity);
}
protected ByteBuffer allocateDirect(int initialCapacity) {
protected void freeDirect(ByteBuffer buffer) {
*********
内部类:InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf
private static final class InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf extends UnpooledUnsafeNoCleanerDirectByteBuf {
InstrumentedUnpooledUnsafeNoCleanerDirectByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
super(alloc, initialCapacity, maxCapacity);
}
ByteBuffer reallocateDirect(ByteBuffer oldBuffer, int initialCapacity) {
protected ByteBuffer allocateDirect(int initialCapacity) {
protected void freeDirect(ByteBuffer buffer) {
*********
内部类:InstrumentedUnpooledHeapByteBuf
private static final class InstrumentedUnpooledHeapByteBuf extends UnpooledHeapByteBuf {
InstrumentedUnpooledHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
super(alloc, initialCapacity, maxCapacity);
}
protected byte[] allocateArray(int initialCapacity) {
protected void freeArray(byte[] array) {
*********
内部类:InstrumentedUnpooledUnsafeHeapByteBuf
private static final class InstrumentedUnpooledUnsafeHeapByteBuf extends UnpooledUnsafeHeapByteBuf {
InstrumentedUnpooledUnsafeHeapByteBuf(UnpooledByteBufAllocator alloc, int initialCapacity, int maxCapacity) {
super(alloc, initialCapacity, maxCapacity);
}
protected byte[] allocateArray(int initialCapacity) {
protected void freeArray(byte[] array) {
PreferHeapByteBufAllocator:优先分配堆内存
public final class PreferHeapByteBufAllocator implements ByteBufAllocator {
private final ByteBufAllocator allocator;
public PreferHeapByteBufAllocator(ByteBufAllocator allocator) {
public ByteBuf buffer() {
public ByteBuf buffer(int initialCapacity) {
public ByteBuf buffer(int initialCapacity, int maxCapacity) {
public ByteBuf ioBuffer() {
public ByteBuf ioBuffer(int initialCapacity) {
public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) {
public ByteBuf heapBuffer() {
public ByteBuf heapBuffer(int initialCapacity) {
public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) {
public ByteBuf directBuffer() {
public ByteBuf directBuffer(int initialCapacity) {
public ByteBuf directBuffer(int initialCapacity, int maxCapacity) {
public CompositeByteBuf compositeBuffer() {
public CompositeByteBuf compositeBuffer(int maxNumComponents) {
public CompositeByteBuf compositeHeapBuffer() {
public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) {
public CompositeByteBuf compositeDirectBuffer() {
public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) {
public boolean isDirectBufferPooled() {
public int calculateNewCapacity(int minNewCapacity, int maxCapacity) {
PreferredDirectByteBufAllocator:优先分配直接内存
public final class PreferredDirectByteBufAllocator implements ByteBufAllocator {
private ByteBufAllocator allocator;
public PreferredDirectByteBufAllocator() {
public void updateAllocator(ByteBufAllocator allocator) {
public ByteBuf buffer() {
public ByteBuf buffer(int initialCapacity) {
public ByteBuf buffer(int initialCapacity, int maxCapacity) {
public ByteBuf ioBuffer() {
public ByteBuf ioBuffer(int initialCapacity) {
public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) {
public ByteBuf heapBuffer() {
public ByteBuf heapBuffer(int initialCapacity) {
public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) {
public ByteBuf directBuffer() {
public ByteBuf directBuffer(int initialCapacity) {
public ByteBuf directBuffer(int initialCapacity, int maxCapacity) {
public CompositeByteBuf compositeBuffer() {
public CompositeByteBuf compositeBuffer(int maxNumComponents) {
public CompositeByteBuf compositeHeapBuffer() {
public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) {
public CompositeByteBuf compositeDirectBuffer() {
public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) {
public boolean isDirectBufferPooled() {
public int calculateNewCapacity(int minNewCapacity, int maxCapacity) {
使用示例
Test
public class Test {
public static void test(){
ByteBuf buf = Unpooled.buffer(); //分配非池化堆内存
ByteBuf buf2 = Unpooled.directBuffer(); //分配非池化直接内存
ByteBuf buf3 = UnpooledByteBufAllocator.DEFAULT.buffer();
ByteBuf buf4 = UnpooledByteBufAllocator.DEFAULT.ioBuffer();
ByteBuf buf5 = UnpooledByteBufAllocator.DEFAULT.heapBuffer();
ByteBuf buf6 = UnpooledByteBufAllocator.DEFAULT.directBuffer();
ByteBuf buf7 = PooledByteBufAllocator.DEFAULT.buffer();
ByteBuf buf8 = PooledByteBufAllocator.DEFAULT.ioBuffer();
ByteBuf buf9 = PooledByteBufAllocator.DEFAULT.heapBuffer();
ByteBuf buf10 = PooledByteBufAllocator.DEFAULT.directBuffer();
}
public static void test2(){ //hasArray()、hasMemoryAddress()
ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer();
System.out.println(buf.hasArray());
System.out.println(buf.hasMemoryAddress());
//System.out.println(buf.memoryAddress());
ByteBuf buf2 = PooledByteBufAllocator.DEFAULT.directBuffer();
System.out.println(buf2.hasArray());
System.out.println(buf2.hasMemoryAddress());
System.out.println(buf2.memoryAddress());
}
public static void test3(){ //byteBuf读写
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf.writeBytes("hello".getBytes(StandardCharsets.UTF_8));
System.out.println(byteBuf.toString(StandardCharsets.UTF_8));
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes, byteBuf.readerIndex(), byteBuf.writerIndex());
System.out.println(new String(bytes));
}
public static void test4(){
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf.writeCharSequence("gtlx",StandardCharsets.UTF_8);
byteBuf.setCharSequence(0,"我",StandardCharsets.UTF_8); //修改英文(英文占1个字节,汉字占3个字节)
System.out.println(byteBuf.toString(StandardCharsets.UTF_8)); //输出:我x
ByteBuf byteBuf2 = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf2.writeCharSequence("瓜田李下",StandardCharsets.UTF_8);
byteBuf2.setCharSequence(3,"我",StandardCharsets.UTF_8); //修改汉字(汉字占3个字节)
System.out.println(byteBuf2.toString(StandardCharsets.UTF_8)); //输出:瓜我李下
}
public static void test5(){
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf.writeBytes("hzw".getBytes(StandardCharsets.UTF_8));
System.out.println((char)byteBuf.getByte(0)); //从指定索引位置往后读1个字节
System.out.println(byteBuf.getCharSequence(0,2,StandardCharsets.UTF_8)); //一个英文占1个字节
ByteBuf byteBuf2 = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf2.writeBytes("海贼王".getBytes(StandardCharsets.UTF_8));
System.out.println(byteBuf2.getCharSequence(0,9,StandardCharsets.UTF_8)); //一个汉字占3个字节
ByteBuf byteBuf3 = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf3.writeCharSequence("瓜田李下",StandardCharsets.UTF_8);
System.out.println(byteBuf3.getCharSequence(0,12,StandardCharsets.UTF_8)); //使用getCharSequence读取(一个汉字占3个字节)
}
public static void test6(){
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.heapBuffer();
byteBuf.writeCharSequence("瓜田李下",StandardCharsets.UTF_8);
System.out.println(byteBuf.readerIndex());
System.out.println(byteBuf.getCharSequence(0,3,StandardCharsets.UTF_8)); //get操作不会引起readerIndex变化
System.out.println("getCharSequence后readerIndex:"+byteBuf.readerIndex());
System.out.println(byteBuf.readCharSequence(12,StandardCharsets.UTF_8)); //read操作会引起readerIndex变化
System.out.println("readCharSequence后readerIndex:"+byteBuf.readerIndex());
}
public static void test7(){
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf.writeCharSequence("火影忍者",StandardCharsets.UTF_8);
System.out.println("初始引用次数:"+byteBuf.refCnt());
byteBuf.touch(); //返回当前对象
System.out.println("执行touch后引用次数:"+byteBuf.refCnt());
byteBuf.retain(); //当前对象引用次数加1,返回当前对象
System.out.println("执行retain后引用次数:"+byteBuf.refCnt());
byteBuf.release(); //释放当前对象(当前对象引用次数减1)
System.out.println("执行release后引用次数:"+byteBuf.refCnt());
}
public static void test8(){
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
byteBuf.writeCharSequence("瓜田李下",StandardCharsets.UTF_8);
ByteBuf copy = byteBuf.copy(0,3); //复制内存(内存不共享)
System.out.println(copy.toString(StandardCharsets.UTF_8));
copy.setCharSequence(0,"大",StandardCharsets.UTF_8);
System.out.println("copy修改:"+byteBuf.toString(StandardCharsets.UTF_8)); //输出:copy修改:瓜田李下
ByteBuf slice = byteBuf.slice(0,6); //截取内存(共享内存)
System.out.println(slice.toString(StandardCharsets.UTF_8));
slice.setCharSequence(0,"小",StandardCharsets.UTF_8);
System.out.println("slice修改:"+byteBuf.toString(StandardCharsets.UTF_8)); //输出:slice修改:小田李下
}
public static void main(String[] args) {
//test();
//test2();
//test3();
//test4();
//test5();
//test6();
//test7();
test8();
}
}



