Java:关于调用 Runtime.freeMemory()、Runtime.totalMemory() 和 Runtime.maxMemory() 的成本

标签 java performance memory garbage-collection jvm

我在内存中有一个 Map 来存储我的对象。我想在内存不足时刷新内存。我现在正在这样做:

void add(K key, V value) {
    if (underPressure()) {
        flush(innerMap);
    }
    innerMap.add(k, v);
}

boolean underPressure() {
    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();
    long freeMemory = rt.freeMemory();

    return (double) freeMemory / maxMemory < threshold;
}

由于每次插入时都会调用 underPressure(),它的成本是多少?据我了解,由于它是一个近似值,它应该由 jvm 以某种方式缓存,但有人真正了解这一点吗?

最佳答案

从 Java 7 开始,不再需要轮询空闲内存。可以注册垃圾收集事件。看到这个帖子:http://www.fasterj.com/articles/gcnotifs.shtml

所以我能想到的最好方法是在垃圾回收后检查可用内存,然后在需要时释放额外空间。

关于Java:关于调用 Runtime.freeMemory()、Runtime.totalMemory() 和 Runtime.maxMemory() 的成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8523517/

相关文章:

java - 过程代码和领域驱动设计风格代码有什么区别?

linux - 哪个更快? `echo` ing 一个变量,或者 `tail` ing 一个长输出文件,或者 `grep` ing 整个东西

c++ - C++程序中按映射结构的内存使用情况

ios - UICollectionViewController : Memory used increasing when scrolling

python - Numpy - 切片图像时的最小内存使用量?

java - 如何使用 Jedis 库建立与 Redis Sentinel 的连接?

java - Jackson 将动态 json 转换为 map

java - Windows 和 Linux 上的不同行为 - build.xml 中的类路径(ant 文件)

c - 提高在 C 中合并两个文件的 IO 性能

c - 如何在 C 中进行无符号饱和加法?