DirectMemory 与 NIO

本机内存DirectMemory,属于C Heap,可以通过参数-XX:MaxDirectMemorySize指定。
如果不指定,该参数的默认值为Xmx的值减去1个Survior区的值。如设置启动参数-Xmx20M -Xmn10M -XX:SurvivorRatio=8,那么申请20M-1M=19M的DirectMemory是没有问题的。


Channel是一个通道,网络数据通过Channel读取和写入。通道与流的不同之处在于通道是双向的,流只是在一个方向上移动(一个流必须是InputStream或者OutputStream的之类),而通道可以用于读、写或者两者同时进行。

因为Channel是全双工的,所以它可以比流更好的映射底层操作系统API。特别是在Unix网络编程模型中,底层操作系统的通道都是全双工的,同时支持读写操作。

实际上,Channel可以分为两大类:用于网络读写的SelectableChannel和用于文件操作的FileChannel。

应用程序中,不能直接对Channel进行读写操作,而必须通过Buffer来进行

NIO的Buffer还提供了一个可以直接访问系统物理内存,而不需要进行用户态和内核态之间的拷贝,即Direct Memory的类-DirectByteBuffe,是Direct I/O模式。
通过byteBuffer.allocateDirect(capacity)在DirectMemory上进行分配。

Buffer

Buffer有四个状态量: mask,position,limit和capacity

mask,the index to which its position will be reset when the reset method is invoked。就是说当reset方法调用后,buffer的position将会被置为mask的值,如果mask存在的话。

position,当前缓存区的位置

limit,缓存区的实际上限

capacity,缓存区的总容量上限

Buffer的几个方法:
clear,makes a buffer ready for a new sequence of channel-read or relative put operations: It sets the limit to the capacity and the position to zero.

就是说要往buffer写数据时,先执行buffer.clear(),使position=0,limit=capacity

flip,makes a buffer ready for a new sequence of channel-write or relative get operation:It sets the limit to the current position and then sets the position to zero.

就是说当从buffer中读数据写入channel时,先执行flip(),使limit=position,position=0

rewind,makes a buffer ready for re-reading the data that it already contains:It leaves the limit unchanged and sets the position to zero.

当要重新读取buffer中的内容时,先执行rewind(),将position=0.否则报java.nio.BufferUnderflowException异常

猜你喜欢

转载自laomn.iteye.com/blog/2422227
NIO
今日推荐