如何查看应用程序正在使用的当前堆大小?
2022-08-31 13:33:35
我想我在 NetBeans 中将堆大小增加到 1 GB,因为我将配置更改为如下所示:
netbeans_default_options="-J-Xmx1g ......
重新启动 NetBeans 后,我能否确定我的应用程序现在有 1 GB?
有没有办法验证这一点?
我想我在 NetBeans 中将堆大小增加到 1 GB,因为我将配置更改为如下所示:
netbeans_default_options="-J-Xmx1g ......
重新启动 NetBeans 后,我能否确定我的应用程序现在有 1 GB?
有没有办法验证这一点?
使用以下代码:
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
了解它对我来说很有用。
public class CheckHeapSize {
public static void main(String[] args) {
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
System.out.println("heap size: " + formatSize(heapSize));
System.out.println("heap max size: " + formatSize(heapMaxSize));
System.out.println("heap free size: " + formatSize(heapFreeSize));
}
public static String formatSize(long v) {
if (v < 1024) return v + " B";
int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
}
}