有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

垃圾收集Java将最大堆大小(Xmx)设置为物理内存的一部分

JDK 8中,默认的最大堆大小为

1/4th of the physical memory or 1GB

并且可以使用-Xmx开关覆盖它:

You can override this default using the -Xmx command-line option.

Xmx开关使用字节,而不是分数。是否有一种简单的方法将最大堆设置为机器物理内存的X%

编辑:

为什么,你问?首先,好奇。我觉得很奇怪,默认的Xmx是用物理内存的一小部分来定义的,但只要我一碰它,它就是一个绝对值。其次,如果我将相同(或类似)的应用程序部署到两个不同的服务器上,并且其中一个服务器具有更多的物理内存,那么我希望可以选择自动让JVM利用额外的内存。这并不总是有意义的,但有时是有意义的

显而易见的解决方案是使用一个shell脚本来检查可用空间量并计算Xmx,但这似乎是一个笨拙的解决方案。我想用纯Java应该是可能的


共 (2) 个答案

  1. # 1 楼答案

    你可能得自己做。假设你想要windows版本, 获取最大内存量(解析类似wmic ComputerSystem get TotalPhysicalMemory),计算其中的1/4,并将其设置为-Xmx选项

    我想问你为什么需要一定比例的物理内存。最大内存量不应影响应用程序的内存使用,如果是这样,应用程序应自行处理

  2. # 2 楼答案

    Java 8u191 (October 16, 2018)以来,有三个专用的JVM选项可以控制堆大小,将其作为可用内存的一部分。它们被记录在案here

    请注意,与其名称相反,MinRAMPercentage设置最大堆大小

    -XX:InitialRAMPercentage=percent

    Sets the initial amount of memory that the JVM will use for the Java heap before applying ergonomics heuristics as a percentage of the maximum amount determined as described in the -XX:MaxRAM option. The default value is 1.5625 percent.

    -XX:MaxRAMPercentage=percent

    Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a percentage of the maximum amount determined as described in the -XX:MaxRAM option. The default value is 25 percent.

    -XX:MinRAMPercentage=percent

    Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a percentage of the maximum amount determined as described in the -XX:MaxRAM option for small heaps. A small heap is a heap of approximately 125 MB. The default value is 50 percent.

    以下是使用jdk 11u10在x64上使用docker运行的一些示例:

    docker run memory <limit> openjdk:11 java -XX:MaxRAMPercentage=25 -XX:MinRAMPercentage=50 -XX:InitialRAMPercentage=5 -XX:+PrintFlagsFinal 2>&1 | grep HeapSize

    | Memory Limit | Initial Heap Size | Max Heap Size    |
    |       |         -|         |
    | 100Mi        | 10485760 (~10%)   | 52428800 (~50%)  |
    | 256Mi        | 27262976 (~10%)   | 132120576 (~50%) |
    | 512Mi        | 54525952 (~10%)   | 134217728 (~25%) |
    | 1Gi          | 109051904 (~10%)  | 268435456 (~25%) |