ByteBuffer vs. DirectByteBuffer

-XX:MaxDirectMemorySize
This options specifies the maximum total size of java.io.nio(New I/O package) direct buffer allocations.
Format:
-XX:MaxDirectMemorySize=size[g|G|m|M|k|K]
Example:
java -XX:MaxDirectMemorySize=2g myApp

Java 2 SE 6 doc :
Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer’s content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system’s native I/O operations.
DirectBuffer通过免去中间交换的内存拷贝, 提升IO处理速度;
Java 2 SE 6 doc :
The contents of direct buffers may reside outside of the normal garbage-collected heap, and so their impact upon the memory footprint of an application might not be obvious.
DirectBuffer在-XX:MaxDirectMemorySize=xxM大小限制下[1], 使用Heap之外的内存, GC对此”无能为力”[2] ,也就意味着规避了在高负载下频繁的GC过程对应用线程的中断影响.

一、应用场景:
大量原生类型数据使用
频繁IO操作
系统处理响应速度要求快且稳定
典型场景是网络数据传输, 可考虑合理应用DirectBuffer eg.jetty用来处理和socket通信使用了DirectByteBuffer

二、取舍:
1.堆缓冲区的性能已经相当高,若无必要,使用堆缓冲区足矣。若确实有提升性能的必要时,再考虑使用本地缓冲区。
2.为JVM分配堆内存时,并不是越大越好,堆内存越大,本地内存就越小,根据具体情况决定,主要针对32位机器,64位机器上不存在该问题

MappedByteBuffer不受-XX:MaxDirectMemorySize=xxM大小限制.

三、回收DirectByteBuffer
http://www.oschina.net/code/snippet_95947_3450

两种缓冲区对应的API如下:
JVM堆缓冲区:ByteBuffer.allocate(size)
本地缓冲区:ByteBuffer.allocateDirect(size)
堆缓冲区从堆空间中分配,本地缓冲区在本地内存中分配,由于32位系统的进程最大可用内存为4G,堆内存分配较多,则本地内存可用空间就会减少。
此种情况堆内存较大,JVM GC长时间不进行垃圾回收,由于直接缓冲区被JVM包装成DirectByteBuffer得不到释放,相应的就不会调用JNI方法释放本地内存,本地内存
不断分配最终导致OutOfMemoryError.

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/23937368/viewspace-1057660/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/23937368/viewspace-1057660/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值