当不再需要时,JVM 是否会将空闲内存返还给操作系统?

2022-01-16 00:00:00 memory jvm java heap-memory

我有一个应用程序暂时需要一定数量的内存/堆用于某些进程.给定一个合理的 JVM 最大堆大小值作为选项,JVM 从一个小堆开始,并根据需要向操作系统请求更多内存.

I have an application that temporarily needs some certain amount of memory/heap for some processes. Given a reasonable value of maximum heap size to the JVM as an option, the JVM starts with a little heap and requests more memory from the OS on demand.

我的问题是,当我的应用程序不再需要太多内存时,JVM 是否会将额外的内存返还给操作系统(例如,用于其他进程).目前,我的应用程序似乎永远保留了该内存,即使不再需要.

My question is, if that additional memory will be given back by the JVM to the OS (e.g. for other processes) when there is no need for much memory anymore by my application. Currently my application seems to hold that memory forever, even when not needed anymore.

推荐答案

JVM确实将内存返回给操作系统,但只是很不情愿,因为它可能很快又需要它,而从操作系统获取内存是一个相对昂贵的操作.

The JVM does return memory to the OS, but only very reluctantly, since it may need it again soon, and getting memory from the OS is a relatively expensive operation.

如果您希望 JVM 更急切地将内存返回给操作系统,您可以使用 Oracle JVM的调优参数,具体是-XX:MaxHeapFreeRatio-XX:MinHeapFreeRatio

If you want the JVM to return memory to the OS more eagerly, you can use the tuning parameters of the Oracle JVM, specifically -XX:MaxHeapFreeRatio and -XX:MinHeapFreeRatio

相关文章