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

查看:27
本文介绍了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.

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

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) 的这个样本可能会有用.

我最初提供了这个样本(链接到威廉·布伦德尔对另一个主题的回答).该主题的创建者 (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();

Christian 通过声明 Runtime.getRuntime().freeMemory() 实际上返回了所谓的可推测的空闲内存来结束他的回答;即使未来的内存分配没有超过该函数返回的值,如果 Java 虚拟机还没有收到主机系统分配的实际内存块,java.lang.OutOfMemoryError 仍可能产生.

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 提出的问题,由 Stones333 关于确定使用的默认 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天全站免登陆