Java中的DirectByteBuffer是如何被回收的


在SunJDK中,java.nio.DirectByteBuffer是由ByteBuffer#allocateDirect(int)創建的,它有一個類型為sun.misc.Cleaner的字段,Cleaner繼承了java.lang.ref.PhantomReference(虛引用).
DirectByteBuffer創建時cleaner字段賦值,傳入一個Runnable類型的Deallocator對象(用於釋放內存)

cleaner = Cleaner.create(this, new Deallocator(base, size, cap));

Cleaner被收集並且即將移入關聯的引用隊列時,GC收集相關的線程通過ReferenceHandlerCleaner類型的Reference實例特殊處理:將引用實例向下轉型為Cleaner,然后調用Cleaner#clean(),最終會回到調用DirectByteBuffer$Deallocator#run(),進而調用Unsafe#freeMemory(long).

可以看到,並沒有對Object#finalize()的調用.

總之,如果釋放對DirectByteBuffer實例的引用,一般就不會耗盡內存,只要垃圾收集器有機會注意到這種情況,之后它的引用處理線程就會執行上述過程.

  • Cleaner對象
    虛引用的子類型.對象構造時傳入一個Runnable用於在引用處理線程執行時調用.

  • Reference.java 注意本代碼的第55行

    private static class ReferenceHandler extends Thread {

        private static void ensureClassInitialized(Class<?> clazz) {
            try {
                Class.forName(clazz.getName(), true, clazz.getClassLoader());
            } catch (ClassNotFoundException e) {
                throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
            }
        }

        static {
            // pre-load and initialize InterruptedException and Cleaner classes
            // so that we don't get into trouble later in the run loop if there's
            // memory shortage while loading/initializing them lazily.
            ensureClassInitialized(InterruptedException.class);
            ensureClassInitialized(Cleaner.class);
        }

        ReferenceHandler(ThreadGroup g, String name) {
            super(g, name);
        }

        public void run() {
            while (true) {
                tryHandlePending(true);
            }
        }
    }

    /**
     * Try handle pending {@link Reference} if there is one.<p>
     * Return {@code true} as a hint that there might be another
     * {@link Reference} pending or {@code false} when there are no more pending
     * {@link Reference}s at the moment and the program can do some other
     * useful work instead of looping.
     *
     * @param waitForNotify if {@code true} and there was no pending
     * {@link Reference}, wait until notified from VM
     * or interrupted; if {@code false}, return immediately
     * when there is no pending {@link Reference}.
     * @return {@code true} if there was a {@link Reference} pending and it
     * was processed, or we waited for notification and either got it
     * or thread was interrupted before being notified;
     * {@code false} otherwise.
     */
    static boolean tryHandlePending(boolean waitForNotify) {
        Reference<Object> r;
        Cleaner c;
        try {
            synchronized (lock) {
                if (pending != null) {
                    r = pending;
                    // 'instanceof' might throw OutOfMemoryError sometimes
                    // so do this before un-linking 'r' from the 'pending' chain...
                    c = r instanceof Cleaner ? (Cleaner) r : null;
                    // unlink 'r' from 'pending' chain
                    pending = r.discovered;
                    r.discovered = null;
                } else {
                    // The waiting on the lock may cause an OutOfMemoryError
                    // because it may try to allocate exception objects.
                    if (waitForNotify) {
                        lock.wait();
                    }
                    // retry if waited
                    return waitForNotify;
                }
            }
        } catch (OutOfMemoryError x) {
            // Give other threads CPU time so they hopefully drop some live references
            // and GC reclaims some space.
            // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above
            // persistently throws OOME for some time...
            Thread.yield();
            // retry
            return true;
        } catch (InterruptedException x) {
            // retry
            return true;
        }

        // Fast path for cleaners
        if (c != null) {
            c.clean();
            return true;
        }

        ReferenceQueue<? super Object> q = r.queue;
        if (q != ReferenceQueue.NULL) q.enqueue(r);
        return true;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM