简体   繁体   English

是否有一种可移植的方式让Java检查最大RAM量?

[英]Is there a portable way for Java to check the maximum amount of RAM?

I'm writing a Java application that needs to check the maximum amount of RAM available in the system (not the one available for the VM). 我正在编写一个Java应用程序,需要检查系统中可用的最大RAM(不是VM可用的RAM)。 Is there a portable way to do so? 有可行的方法吗?

Thanks a lot :-) 非常感谢 :-)

JMX you can access the FreePhysicalMemorySize and TotalPhysicalMemorySize attributes of java.lang:type=OperatingSystem. 在JMX中,您可以访问java.lang的FreePhysicalMemorySize和TotalPhysicalMemorySize属性:type = OperatingSystem。 These attributes are not really documented in the JavaDocs so they are probably not guaranteed on all JVMs and platforms, but they were available to me (using Sun's JVM). JavaDocs中并未真正记录这些属性,因此可能无法在所有JVM和平台上保证这些属性,但我们可以使用它们(使用Sun的JVM)。

In your Java code you can get access to the MBean via: ManagementFactory.getOperatingSystemMXBean() 在Java代码中,您可以通过以下方式访问MBean:ManagementFactory.getOperatingSystemMXBean()

These properties are documented in the JavaDoc for Sun's implementation so I think you may rely on them if your application runs on their JVM. 这些属性记录在JavaDoc for Sun的实现中,因此我认为如果您的应用程序在其JVM上运行,您可能会依赖它们。

Short answer: no , no portable way to get total RAM. 简答: ,没有可移植的方式来获得总RAM。

Of course, there is a very easy way to get total JVM memory ( java.lang.Runtime.maxMemory() ), but this is not what you're after. 当然,有一种非常简单的方法可以获得总JVM内存( java.lang.Runtime.maxMemory() ),但这不是你想要的。

To get total system RAM size, you will need to resort to native system calls (which are totally not portable). 要获得总系统RAM大小,您需要求助于本机系统调用(完全不可移植)。

you can use JNI call to query your native OS 您可以使用JNI调用来查询本机操作系统

but you will have to restart the JVMwith new memory arguments if you want more memory for the JMV 但如果您想为JMV提供更多内存,则必须使用新的内存参数重新启动JVM

"maximum amount of RAM available" - so not the physical RAM installed I assume? “最大可用RAM量” - 所以我假设没有安装物理RAM吗? But the part that's (1) accessible to the OS, (2) not in use to store OS code, and (3) not in use to store OS data? 但是(1)操作系统可以访问的部分,(2)不用于存储操作系统代码,(3)不用于存储操作系统数据?

The problem is that this answer changes every millisecond as the OS flushes dirty pages to disk, thus reducing part (3) above. 问题是当OS将脏页刷新到磁盘时,这个答案每毫秒都会改变,从而减少了上面的第(3)部分。 And if RAM is really needed, the OS will often swap parts of itself out, so the amount of RAM allocated for (2) is also fuzzy. 如果真的需要RAM,操作系统通常会将自身的部分交换掉,因此为(2)分配的RAM量也是模糊的。

And we'll probably need to skip the case of a virtualized system where the OS itself runs in a VM, so you'd have a JVM in an OS in a VM. 我们可能需要跳过虚拟化系统的情况,其中操作系统本身在VM中运行,因此您在VM中的操作系统中有一个JVM。

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

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