有没有办法在不使用时降低 Java 堆? [英] Is there a way to lower Java heap when not in use?

查看:25
本文介绍了有没有办法在不使用时降低 Java 堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个 Java 应用程序并努力优化其内存使用.据我所知,我正在遵循正确垃圾收集的准则.但是,即使不需要,我的堆似乎也处于最大大小.

I'm working on a Java application at the moment and working to optimize its memory usage. I'm following the guidelines for proper garbage collection as far as I am aware. However, it seems that my heap seems to sit at its maximum size, even though it is not needed.

当计算机无人使用时,我的程序每小时运行一次资源密集型任务.此任务使用了相当大的内存块,但在任务完成后立即将其全部释放.NetBeans 分析器显示内存使用情况如下所示:

My program runs a resource intensive task once an hour, when the computer is not in use by a person. This task uses a decent chunk of memory, but then frees it all immediately after the task completes. The NetBeans profiler reveals that memory usage looks like this:

我真的很想在不使用时将所有这些堆空间还给操作系统.我没有理由完全依赖它,而该程序至少还有一个小时不会做任何事情.

I'd really like to give all of that heap space back to the OS when not in use. There is no reason for me to hog it all while the program won't even be doing anything for at least another hour.

这可能吗?谢谢.

推荐答案

你也许可以使用 -XX:MaxHeapFreeRatio - 这是空闲堆的最大百分比(默认为 70)在 GC 缩小它之前.也许将它设置得低一点(40 或 50?)然后使用 System.gc() 可能会花费一些时间来获得所需的行为?

You could perhaps play around with -XX:MaxHeapFreeRatio - this is the maximum percentage (default 70) of the heap that is free before the GC shrinks it. Perhaps setting it a bit lower (40 or 50?) and then using System.gc() might go some lengths to get you the desired behaviour?

没有办法强制这种情况发生,但是,您可以尝试并鼓励 JVM 这样做,但您不能只是在需要时将内存拉走.虽然上述可能会缩小堆,但该内存不一定会直接交还给操作系统(尽管在最近的 JVM 实现中确实如此.)

There's no way to force this to happen however, you can try and encourage the JVM to do so but you can't just yank memory away as and when you want to. And while the above may shrink the heap, that memory won't necessarily be handed straight back to the OS (though in recent implementations of the JVM it does.)

这篇关于有没有办法在不使用时降低 Java 堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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