簡體   English   中英

Java:調用Runtime.freeMemory(),Runtime.totalMemory()和Runtime.maxMemory()的代價

[英]Java: on the cost of calling Runtime.freeMemory(), Runtime.totalMemory() and Runtime.maxMemory()

我在內存中有一個存儲我的對象的Map 當我內存不足時,我想要記憶。 我現在正在這樣做:

void add(K key, V value) {
    if (underPressure()) {
        flush(innerMap);
    }
    innerMap.add(k, v);
}

boolean underPressure() {
    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();
    long freeMemory = rt.freeMemory();

    return (double) freeMemory / maxMemory < threshold;
}

因為在每個插入物處調用underPressure() ,它有多貴? 根據我的理解,因為它是一個近似值,它應該以某種方式被jvm 緩存 ,但是有沒有人真正了解這個?

從Java 7開始,不再需要輪詢空閑內存。 可以注冊垃圾收集事件。 請看這篇文章: http//www.fasterj.com/articles/gcnotifs.shtml

所以我能想到的最好方法是在垃圾收集后檢查可用內存,然后在需要時釋放額外空間。

為什么不使用JMXBeans來執行此操作。 它旨在簡化這種操作..

來自文檔......

API提供對以下信息的訪問:

 Number of classes loaded and threads running Virtual machine uptime, system properties, and JVM input arguments Thread state, thread contention statistics, and stack trace of live threads Memory consumption Garbage collection statistics Low memory detection On-demand deadlock detection Operating system information 

具體請參閱MemoryPoolMXBean中的示例代碼

不是直接回答你的問題,但正如評論中已經說過的那樣, freeMemory會計算可用內存而不是GC之后可用的內存,因此如果你在GC運行之前調用freeMemory ,你可能會認為你達到了“underPressure”限制但是你可以在下一次GC運行后獲得足夠的可用內存。

另一種方法可能是創建一個可輕松訪問的對象,並檢查GC是否聲明了它:

就像是:

SoftReference<Object> sr = new SoftReference<Object>(new Object(),new ReferenceQueue<Object>());
public boolean underPressure(){
    if (sr.isEnqueued()) {
        // recreate object to monitor
        sr = new SoftReference<Object>(new Object(),new ReferenceQueue<Object>());
        return true;
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM