2013-02-18 28 views

回答

2

//獲取堆的電流的大小以字節

long heapSize = Runtime.getRuntime().totalMemory(); 

//獲取字節的堆的最大大小。堆不能超出這個尺寸。任何嘗試都會導致OutOfMemoryException異常。

long heapMaxSize = Runtime.getRuntime().maxMemory(); 

//以堆爲單位獲取堆內可用內存量。垃圾收集後,這個大小將增加,並且隨着新對​​象的創建而減少。

long heapFreeSize = Runtime.getRuntime().freeMemory(); 
+0

對你有用嗎? – 2013-02-18 13:27:50

2

如果你想從你的程序本身檢查它,使用Runtime類的方法:

Runtime.getRuntime().freeMemory() 
Runtime.getRuntime().maxMemory() 

如果這是確定讓你從你的程序外檢查堆大小,你應該使用JVisualVM。您可以在JDK的bin文件夾中找到它。只需啓動它,並附加到您的Java程序,以瞭解您的程序堆使用情況。它將顯示堆使用情況的圖形,使您可以輕鬆找到程序運行的最大堆大小。

4

獲取當前堆大小:

public static long getHeapSize(){ 
    int mb = 1024*1024; 

    //Getting the runtime reference from system 
    Runtime runtime = Runtime.getRuntime(); 

    return ((runtime.totalMemory() - runtime.freeMemory())/mb); 
} 
1

參見運行時信息:

Runtime.getRuntime().maxMemory(); 
Runtime.getRuntime().totalMemory(); 
Runtime.getRuntime().freeMemory(); 
2

其他的答案提供了通過調用Runtime.getRuntime()做的力學totalMemory()和maxMemory (),但要非常小心 - 給定的答案在給定的時刻只會是真實的。在GC之後,totalMemory()將會改變(向下!)。您無法始終準確地查看「系統中存在多少活物」 - 因爲這正是GC計算的結果,而且成本昂貴。

使用JMX(見GC豆,等..)將與輪詢幫助,但再次,它是隨着時間的推移的樣本。

所以我不確定你在這裏試圖解決什麼...

相關問題