zoukankan      html  css  js  c++  java
  • Direct ByteBuffer学习

     ByteBuffer有两种一种是heap ByteBuffer,该类对象分配在JVM的堆内存里面,直接由Java虚拟机负责垃圾回收,一种是direct ByteBuffer是通过jni在虚拟机外内存中分配的。通过jmap无法查看该快内存的使用情况。只能通过top来看它的内存使用情况。

    JVM堆内存大小可以通过-Xmx来设置,同样的direct ByteBuffer可以通过-XX:MaxDirectMemorySize来设置,此参数的含义是当Direct ByteBuffer分配的堆外内存到达指定大小后,即触发Full GC。注意该值是有上限的,默认是64M,最大为sun.misc.VM.maxDirectMemory(),在程序中中可以获得-XX:MaxDirectMemorySize的设置的值。

        @Test
        public void testBits() throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
        {
    //        System.out.println("maxMemoryValue:"+sun.misc.VM.maxDirectMemory()); 
            ByteBuffer buffer=ByteBuffer.allocateDirect(0);
            Class c = Class.forName("java.nio.Bits");  
            Field maxMemory = c.getDeclaredField("maxMemory");  
            maxMemory.setAccessible(true);  
            synchronized (c) {  
                Long maxMemoryValue = (Long)maxMemory.get(null);  
                System.out.println("maxMemoryValue:"+maxMemoryValue);  
            }  
        }

    下面要谈到垃圾回收机制:direct ByteBuffer通过full gc来回收内存的,direct ByteBuffer会自己检测情况而调用system.gc(),但是如果参数中使用了DisableExplicitGC那么就无法回收该快内存了,-XX:+DisableExplicitGC标志自动将System.gc()调用转换成一个空操作,就是应用中调用System.gc()会变成一个空操作。那么如果设置了就需要我们手动来回收内存了

        @Test
        public void testAllocateDirector() throws Exception{
            ByteBuffer buffer=ByteBuffer.allocateDirect(1024);
            Field cleanerField = buffer.getClass().getDeclaredField("cleaner");
            cleanerField.setAccessible(true);
            Cleaner cleaner = (Cleaner) cleanerField.get(buffer);
            cleaner.clean();
        }

    那么除了FULL GC还有别的能回收direct ByteBuffer吗?CMS GC会回收Direct ByteBuffer的内存,CMS主要是针对old space空间的垃圾回收。但是是Oracle JDK 6u32以后的版本

    讲了这么多谈下使用场景

    1:多用网络编程中用到,实现zero copy,数据不需要再native memory和jvm memory中来回copy

    2:由于造和析构Direct Buffer时间成本高,建议使用缓冲池,参见netty的实现

  • 相关阅读:
    ABBYY Cup 3.0G3. Good Substrings
    Codeforces Beta Round #94 (Div. 1 Only)B. String sam
    hdu5421Victor and String 两端加点的pam
    loj#2059. 「TJOI / HEOI2016」字符串 sam+线段树合并+倍增
    Codeforces Round #349 (Div. 1)E. Forensic Examination
    ACM-ICPC World Finals 2019 G.First of Her Name
    51nod1647 小Z的trie
    LOJ #10222. 「一本通 6.5 例 4」佳佳的 Fibonacci 题解
    POJ 2443 Set Operation 题解
    CSP-J 2019游记
  • 原文地址:https://www.cnblogs.com/gaoxing/p/4302088.html
Copyright © 2011-2022 走看看