netty学习之一:java.nio.ByteBuffer

Java缓冲区操作详解
本文详细解析了Java中ByteBuffer类的使用,包括容量、位置、限制等属性的初始化及翻转方法的应用,通过实例展示了如何将字符串转换为字节缓冲,并进行数据读取的过程。


public class App {
	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(88);
		String value = "权威指南";
		buffer.put(value.getBytes());
		System.out.println(buffer.capacity());
		System.out.println(buffer.position());
		System.out.println(buffer.limit());
		System.out.println("===================");
		buffer.flip();
		int remaining = buffer.remaining();
		System.out.println(buffer.capacity());
		System.out.println(buffer.position());
		System.out.println(buffer.limit());

		byte[] vArray = new byte[remaining];
		ByteBuffer bb = buffer.get(vArray);
		String dcode = new String(vArray);
		System.out.println(dcode);
	}
}

以上代码的结果:

88
12
88
===================
88
0
12

权威指南

1、从代码运行结果可以分析出,开始初始化capacity,position,limit分别是88,12,88,

2、从源码角度解析:
a、  public static ByteBuffer allocate(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
    }

执行new HeapByteBuffer(capacity, capacity); capacity赋值为88,limit为88
执行buffer.put(value.getBytes()); position(position() + length);将position赋值为12

b、flip()方法实现: 
<pre name="code" class="java"> public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }
将limit赋值为12,position赋值为0,这样就可以正确读取数据
之前put的时候发生:
 public ByteBuffer put(byte[] src, int offset, int length) {
        checkBounds(offset, length, src.length);
        if (length > remaining())
            throw new BufferOverflowException();
        int end = offset + length;
        for (int i = offset; i < end; i++)
            this.put(src[i]);
        return this;
    }

这里的end是12
读取的时候也要从0,12开始读取,不然会错误读,以下是读取源码:
   public ByteBuffer get(byte[] dst, int offset, int length) {
        checkBounds(offset, length, dst.length);
        if (length > remaining())
            throw new BufferUnderflowException();
        int end = offset + length;
        for (int i = offset; i < end; i++)
            dst[i] = get();
        return this;
    }













11:24:25.865 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework 11:24:25.868 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false 11:24:25.869 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - Java version: 8 11:24:25.869 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available 11:24:25.869 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.storeFence: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - direct buffer constructor: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable prior to Java9 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - java.nio.DirectByteBuffer.<init>(long, int): available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - sun.misc.Unsafe: available 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.tmpdir: C:\Users\admin\AppData\Local\Temp (java.io.tmpdir) 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.bitMode: 64 (sun.arch.data.model) 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - Platform: Windows 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.maxDirectMemory: 7570718720 bytes 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.uninitializedArrayAllocationThreshold: -1 11:24:25.872 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.CleanerJava6 - java.nio.ByteBuffer.cleaner(): available 11:24:25.872 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.noPreferDirect: false 11:24:26.010 [main] DEBUG io.grpc.netty.shaded.io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 48 11:24:26.018 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.initialSize: 1024 11:24:26.018 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.maxSize: 4096 11:24:26.021 [main] DEBUG io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false 11:24:26.021 [main] DEBUG io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512 11:24:26.024 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - org.jctools-core.MpscChunkedArrayQueue: available客户端运行结果如下,请分析并提出解决方案
08-26
16:09:09.019 [nioEventLoopGroup-6-2] ERROR c.F.C.I.G.GNGateServerReceiver - [channelRead,62] - java.lang.NullPointerException: Cannot invoke "java.nio.ByteBuffer.position(int)" because "this.msg_buff" is null at com.FX.Charg.IOT.processor.GNGateMessageProcessor.getMsgData(GNGateMessageProcessor.java:235) at com.FX.Charg.IOT.processor.GNGateMessageProcessor.getDeviceIotSN(GNGateMessageProcessor.java:27) at com.FX.Charg.IOT.processor.EBikeMessageProcessor.parse(EBikeMessageProcessor.java:52) at com.FX.Charg.IOT.processor.Processor.initProcessor(Processor.java:49) at com.FX.Charg.IOT.tcp.TCPServerReceiver.channelRead(TCPServerReceiver.java:53) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1357) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:868) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:1583)
最新发布
08-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值