简体   繁体   English

Java程序使用了多少内存

[英]How much memory is used by Java program

I've had a look around, and I've seen plenty of answers regarding the question of how much memory is being used by the JVM. 我环顾了一下,关于JVM正在使用多少内存的问题,我已经看到了很多答案。 These involve things such as calls to Runtime.totalMemory()/Runtime.freeMemory(). 这些涉及诸如对Runtime.totalMemory()/ Runtime.freeMemory()的调用。

However, these don't take into account garbage collection. 但是,这些未考虑垃圾收集。 For example, say we have a large number of objects set to null, which have not yet been garbage collected. 例如,假设我们有大量设置为null的对象,这些对象尚未被垃圾回收。 Calling Runtime.totalMemory() will show the total memory available as being far below what is actually technically available, as these null objects are still in memory. 调用Runtime.totalMemory()将显示可用总内存远低于实际技术可用的内存,因为这些空对象仍在内存中。

So my question is this: is there any better way, be it in Java itself or data from a third party tool that can be ported into the program, to tell dynamically how much memory is being used by a Java program? 所以我的问题是:有没有更好的方法,无论是Java本身还是来自第三方工具的数据(可以移植到程序中),以动态判断Java程序正在使用多少内存?

EDIT: This needs to be something that can be done in the code itself. 编辑:这需要在代码本身中可以完成。 Short of calling geObjectSize() on every message sent I can't think of another way of doing it. 缺少对发送的每条消息调用geObjectSize()的想法,我想不出另一种方法。

您可以像JProfiler这样的探查器,并为特定程序找出实时使用的内存量。

Typically this information is not known prior to garbage collection. 通常,在垃圾回收之前,此信息是未知的。

After garbage collection, you can compute the amount of currently used memory with Runtime.totalMemory() and Runtime.freeMemory() , as you note. 如您所述,在垃圾回收之后,您可以使用Runtime.totalMemory()Runtime.freeMemory()计算当前使用的内存量。

... say we have a large number of objects set to null ... ...说我们有大量的对象设置为null ...

Objects cannot be set to null. 对象不能设置为null。 You may set references to objects to null. 您可以将对对象的引用设置为null。 Setting a particular reference to an object to null does not immediately mark the object as eligible for collection . 将对对象的特定引用设置为null 不会立即将该对象标记为有资格进行收集

Objects can be collected when they're no longer reachable . 当物体不再可达时可以收集它们。 Part of garbage collection is determining whether an object is no longer reachable. 垃圾收集的一部分是确定对象是否不再可访问。

One thing you could try is to suggest to the virtual machine that it free more memory. 您可以尝试的一件事是建议虚拟机释放更多的内存。 However, this is just a suggestion, so there might actually be more memory available after subsequent garbage collection. 但是,这只是一个建议,因此在后续的垃圾回收之后实际上可能会有更多的可用内存。

public long getUpperBoundOfActiveMemoryUsage() {
    System.gc(); // Suggest that some garbage collection occur.

    return getUsedMemory();
}

public long getUsedMemory() {
    Runtime runtime = Runtime.getRuntime();
    long totalMemory = runtime.totalMemory();
    long freeMemory = runtime.freeMemory();
    long usedMemory = totalMemory - freeMemory;
    return usedMemory;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM