Java获取可用内存 [英] Java get available memory

查看:107
本文介绍了Java获取可用内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好方法可以在运行时为JVM提供可用的剩余内存吗?这种情况的用例是使Web服务在接近内存限制时通过拒绝一个新的错误消息太多的人使用此,请稍后再试",而不是因OutOfMemory错误而突然死亡而接近正常运行,从而失败

Is there any good way to get the remaining memory available to the JVM at run time? The use case of this would be to have web services which fail gracefully when they are nearing their memory limits by refusing new connections with a nice error message "too many people using this, try again later", rather than dying abruptly with an OutOfMemory error.

请注意,这与事先计算/估算每个对象的成本无关.原则上,我可以根据该估算值估算对象占用并拒绝新连接的内存量,但这似乎有点hacky/脆弱.

Note this has nothing to do with calculating/estimating the cost of each object beforehand. In principle I could estimate how much memory my objects take and refuse new connections based on that estimate, but that seems kind of hacky/fragile.

推荐答案

威廉·布伦德尔(William Brendel)的这个样本可能有用.

我最初提供了此示例(链接到William Brendel关于另一个主题的答案).该主题的创建者(Steve M)想要创建一个多平台的Java应用程序.具体来说,用户正试图找到一种方法来评估正在运行的计算机的资源(磁盘空间,CPU和内存使用情况).

I originally provided this sample (linking to William Brendel's answer on another topic). The creator of that topic (Steve M) wanted to create a multi-platform Java application. Specifically, the user was trying to find a means by which to assess the running machine's resources (disk space, CPU and memory usage).

这是该主题给出的答案的内联成绩单.但是,尽管我的回答被标记为已接受,但在该主题上已指出,这不是理想的解决方案.

This is an inline transcript of the answer given in that topic. However, it has been pointed out on this topic that it is not the ideal solution, despite my answer being marked as accepted.

public class Main {
  public static void main(String[] args) {
  /* Total number of processors or cores available to the JVM */
  System.out.println("Available processors (cores): " + 
  Runtime.getRuntime().availableProcessors());

  /* Total amount of free memory available to the JVM */
  System.out.println("Free memory (bytes): " + 
  Runtime.getRuntime().freeMemory());

  /* This will return Long.MAX_VALUE if there is no preset limit */
  long maxMemory = Runtime.getRuntime().maxMemory();
  /* Maximum amount of memory the JVM will attempt to use */
  System.out.println("Maximum memory (bytes): " + 
  (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));

  /* Total memory currently in use by the JVM */
  System.out.println("Total memory (bytes): " + 
  Runtime.getRuntime().totalMemory());

  /* Get a list of all filesystem roots on this system */
  File[] roots = File.listRoots();

  /* For each filesystem root, print some info */
  for (File root : roots) {
    System.out.println("File system root: " + root.getAbsolutePath());
    System.out.println("Total space (bytes): " + root.getTotalSpace());
    System.out.println("Free space (bytes): " + root.getFreeSpace());
    System.out.println("Usable space (bytes): " + root.getUsableSpace());
  }
 }
}

用户克里斯蒂安·弗里斯(Christian Fries)指出,假设Runtime.getRuntime().freeMemory()为您提供了在出现内存不足错误之前可以分配的内存量是错误的.

User Christian Fries points out that it is wrong to assume that Runtime.getRuntime().freeMemory() gives you the amount of memory which may be allocated until an out-of-memory error occurs.

文档Runtime.getRuntime().freeMemory()的签名返回是这样的:

From the documentation, the signature return of Runtime.getRuntime().freeMemory() is as such:

返回::近似于当前可用于将来分配的对象的内存总量,以字节为单位.

Returns: an approximation to the total amount of memory currently available for future allocated objects, measured in bytes.

但是,用户Christian Fries声称此功能可能会被误解.他声称,直到出现内存不足错误(空闲内存)之前可以分配的大概内存量可能由以下公式给出:

However, user Christian Fries claims this function may be misinterpreted. He claims that the approximate amount of memory which may be allocated until an out-of-memory error occurs (the free memory) is likely to be given by:

long presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;

其中allocatedMemory的给出者是:

long allocatedMemory = 
  (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());

这里的关键是空闲内存的概念之间的差异.一件事是操作系统提供的Java虚拟机内存.另一个是Java虚拟机本身实际使用的包括内存块块的字节总数.

The key here is a discrepancy between the concept of free memory. One thing is the memory that the operating system provides the Java Virtual Machine. Another is the total amount of bytes comprising the chunks of blocks of memory actually being used by the Java Virtual Machine itself.

考虑到分配给Java应用程序的内存是由Java虚拟机按块管理的,因此Java虚拟机可用的可用内存数量可能与Java应用程序可用的内存不完全匹配.

Considering that memory given to Java applications is managed in blocks by the Java Virtual Machine, the amount of free memory available to the Java Virtual Machine may not exactly match the memory available for a Java application.

具体地说,克里斯汀·弗里斯(Christian Fries)表示使用-mx-Xmx标志来设置Java虚拟机可用的最大内存量.他指出了以下功能差异:

Specifically, Christian Fries denotes the usage of the -mx or -Xmx flags to set the maximum amount of memory available to the Java Virtual Machine. He notes the following function differences:

/* Returns the maximum amount of memory available to 
   the Java Virtual Machine set by the '-mx' or '-Xmx' flags. */
Runtime.getRuntime().maxMemory();

/* Returns the total memory allocated from the system 
   (which can at most reach the maximum memory value 
   returned by the previous function). */
Runtime.getRuntime().totalMemory();

/* Returns the free memory *within* the total memory 
   returned by the previous function. */
Runtime.getRuntime().freeMemory();

克里斯蒂安总结说,Runtime.getRuntime().freeMemory()实际上返回了所谓的可能的可用内存",从而结束了他的回答.即使将来的内存分配不超过该函数返回的值,如果Java虚拟机尚未收到主机系统分配的实际内存块,也会使用

Christian concludes his answer by stating that Runtime.getRuntime().freeMemory() in fact returns what may be called presumable free memory; even if a future memory allocation does not exceed the value returned by that function, if the Java Virtual Machine has not yet received the actual chunk of memory assigned by the host system, a java.lang.OutOfMemoryError may still be produced.

最后,正确使用的方法将在不同程度上取决于您的应用程序的具体情况.

In the end, the proper method to use will have a varying degree of dependence on the specifics of your application.

我提供了另一个可能有用的链接.这是用户Richard Dormand提出的问题,并由stone333 回答有关确定使用的默认Java堆大小.

I provide another link which may be useful. It is a question made by user Richard Dormand and answered by stones333 about determining the default Java heap size used.

这篇关于Java获取可用内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆