天天看點

DirectByteBuffer記憶體回收筆記

今天在看netty源碼時候又再次遇到了DirectByteBuffer,關于DirectByteBuffer的記憶體回收機制,在netty架構中被封裝的面目全非,但其回收機制也是萬變不離其宗,下面這幾篇簡單易懂的文章就介紹了DirectByteBuffer的概念極其記憶體回收方式,在這裡和大家分享一下:

文章清單
jvm堆外記憶體–DirectByteBuffer
java之HeapByteBuffer&DirectByteBuffer以及回收DirectByteBuffer
NIO DirectByteBuffer 記憶體洩露的測試

關鍵的幾行代碼也黏貼在這,旨在加深印象

public static void sleep(long i) {
        try {
            Thread.sleep(i);
        } catch (Exception e) {
            /*skip*/
        }
    }


    @Test
    public void testDirectByteBufferDeallocation() {

        /**
         DirectByteBuffer構造方法是包私有的,隻能通過工具方法:
         public static ByteBuffer allocateDirect(int capacity)生成對象
         */
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect( *  * );


        System.out.println(byteBuffer.isDirect());
        sleep( * );

        System.out.println("start clean");
        //可以通過作業系統指令檢視堆外記憶體清理前後的記憶體占用
        clean(byteBuffer);
        System.out.println("end clean");

        sleep( * );
    }


    public static void clean(final ByteBuffer byteBuffer) {
        if (byteBuffer.isDirect()) {
            ((DirectBuffer) byteBuffer).cleaner().clean();
        }
    }
           
lhever 

.---.                                                                         
|   |   .              __.....__   .----.     .----.   __.....__              
|   | .'|          .-''         '.  \    \   /    /.-''         '.            
|   |<  |         /     .-''"'-.  `. '   '. /'   //     .-''"'-.  `. .-,.--.  
|   | | |        /     /________\   \|    |'    //     /________\   \|  .-. | 
|   | | | .'''-. |                  ||    ||    ||                  || |  | | 
|   | | |/.'''. \\    .-------------''.   `'   .'\    .-------------'| |  | | 
|   | |  /    | | \    '-.____...---. \        /  \    '-.____...---.| |  '-  
|   | | |     | |  `.             .'   \      /    `.             .' | |      
'---' | |     | |    `''-...... -'      '----'       `''-...... -'   | |      
      | '.    | '.                                                   |_|      
      '---'   '---'  
           

繼續閱讀