通过运行时对象与任务管理器输出 Java 内存使用情况

标签 java memory-leaks heap-memory

我目前使用以下代码打印应用程序中的内存使用信息:

Runtime runtime = Runtime.getRuntime();

NumberFormat format = NumberFormat.getInstance();

long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();

errorLog.warn("free memory: " + format.format(freeMemory / 1024));
errorLog.warn("allocated memory: " + format.format(allocatedMemory / 1024));
errorLog.warn("max memory: " + format.format(maxMemory / 1024));
errorLog.warn("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));

输出看起来类似于以下内容:

Free Memory: 3,471K
Allocated Memory: 29,572K
Max Memory: 253,440K
Total Free Memory: 227,339K

这与我在 JVM 任务管理器中看到的 98,768K 使用情况有何关系?这是我第一次使用 Runtime 类并检查这些值。在我编写的应用程序中寻找可能的内存问题。我看到任务管理器值随着时间的推移慢慢增加,但运行时类项目却没有。虽然最终 Task Mgr 值会急剧下降,我猜这是 GC 正在运行。

最佳答案

托尔内存是:

The total allocated space reserved for the java process.

另请参阅此答案:What is runtime total memory ?

但是任务管理器会报告计算机中 JVM 消耗的总内存。

任务管理器报告操作系统(在本例中为 Windows)分配给运行 JVM 的 Windows 进程的内存,而 Runtime.getTotalMemory() 报告分配给运行执行该方法的线程的当前 java 进程的总内存。 对于每个线程,运行时都是一个实例,“

"Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method." Runtime Javadoc

PS:如果您在 Eclipse 等 IDE 中运行程序,您可能会注意到很大的差异,因为操作系统报告 IDE 消耗的总内存(Eclipse 是一个 Java 程序)加上为运行 Java 程序而生成的 JVM 消耗的内存。 Eclipse 可能会启动不同的 JVM 实例来运行程序。因此,在 eclipse 使用的衍生 JVM 中运行运行时会报告其中的总内存。

关于通过运行时对象与任务管理器输出 Java 内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935718/

相关文章:

java - java.io 包中的缓冲如何优化性能

java - 为什么这段Java/Groovy代码会导致堆内存异常?

java - 使用字符串文字创建字符串常量池的编译器行为

AngularJS - $destroy 是否删除事件监听器?

haskell - 递归列表 zipWith 的空间泄漏

haskell - 空内存配置文件

java - 哪个 Swing 组件适合此设计?

c# - 是否有 C# 的 HttpServerUtility.UrlTokenDecode 的 Java 等效项?

java - 发送SIGTERM时,VM_Exit是如何传递给VM Thread的?由谁传递?

ios - AVAssetWriter 东西泄露