8

我想使用 MapMaker 创建一个缓存大对象的地图,如果没有足够的内存,应该从缓存中删除。这个小演示程序似乎运行良好:

public class TestValue {
    private final int id;
    private final int[] data = new int[100000];

    public TestValue(int id) {
        this.id = id;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalized");
    }  
}  


public class Main {

    private ConcurrentMap<Integer, TestValue> cache;
    MemoryMXBean memoryBean;

    public Main() {
        cache = new MapMaker()
                .weakKeys()
                .softValues()
                .makeMap();
        memoryBean = ManagementFactory.getMemoryMXBean();
    }

    public void test() {
        int i = 0;
        while (true) {
            System.out.println("Etntries: " + cache.size() + " heap: "  
                + memoryBean.getHeapMemoryUsage() + " non-heap: "  
                + memoryBean.getNonHeapMemoryUsage());
            for (int j = 0; j < 10; j++) {
                i++;
                TestValue t = new TestValue(i);
                cache.put(i, t);
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
       }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main m = new Main();
        m.test();
    }

}

然而,当我在我的真实应用程序中做同样的事情时,条目基本上一被添加就从缓存中删除。在我的实际应用程序中,我也使用整数作为键,缓存值是从磁盘读取的包含一些数据的存档块。据我了解,弱引用一旦不再使用就会被垃圾收集,所以这似乎是有道理的,因为键是弱引用。如果我这样创建地图:

    data = new MapMaker()
            .softValues()
            .makeMap();

这些条目永远不会被垃圾收集,并且我的测试程序中出现内存不足错误。TestValue 条目上的 finalize 方法永远不会被调用。如果我将测试方法更改为以下内容:

public void test() {
    int i = 0;
    while (true) {
        for (final Entry<Integer, TestValue> entry :
            data.entrySet()) {
            if (entry.getValue() == null) {
                data.remove(entry.getKey());
            }
        }
        System.out.println("Etntries: " + data.size() + " heap: "
            + memoryBean.getHeapMemoryUsage() + " non-heap: "  
            + memoryBean.getNonHeapMemoryUsage());
        for (int j = 0; j < 10; j++) {
            i++;
            TestValue t = new TestValue(i);
            data.put(i, t);
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
        }
    }
}

从缓存中删除条目并调用 TestValue 对象的终结器,但过了一会儿我也得到了内存不足的错误。

所以我的问题是:使用 MapMaker 创建可用作缓存的地图的正确方法是什么?如果我使用weakKeys,为什么我的测试程序没有尽快删除条目?是否可以将引用队列添加到缓存映射?

4

3 回答 3

8

可能会发生很多事情,但对于使用软值的测试程序:即使您有尚未被垃圾收集的 SoftReferences,您也​​会得到 OutOfMemoryError。需要重复一遍:即使您有尚未清除的 SoftReferences,您也​​会收到 OutOfMemoryError。

SoftReferences 有点奇怪,有关当前机制的描述,请参阅http://jeremymanson.blogspot.com/2009/07/how-hotspot-decides-to-clear_07.html。可能在您的测试用例中,GC 只是没有时间进行两次完整的 GC。

当您使用weakKeys 时,CG 会立即清除它们,而不必等待完全的 GC 暂停。(b/c WeakReferences 被积极收集。)

在我看来,如果你想要一个带有整数键的内存敏感缓存,我认为以下是合适的:

data = new MapMaker().softValues().makeMap();

您可以轻松地编写一个抛出 OutOfMemoryError 的测试程序,但如果您的实际应用程序表现得有些好,并且没有承受太大的压力,那么您可能会没事。SoftReferences 很难做到正确。

如果您需要使用 System.gc() 避免内存不足,我建议您切换到具有固定最大大小的 LRU 映射(参见 java.util.LinkedHashMap 的 javadoc 示例。)它不是并发的,但我希望它最终会给您带来比要求系统执行完全暂停垃圾收集更多次的更好的吞吐量。

哦,关于整数键和weakKeys() 的最后一点说明:MapMaker 在使用弱键或软键时对键使用身份比较,这很难正确做到。见证以下内容:

Map<Integer,String> map = new MapMaker().weakKeys().makeMap();
Integer a = new Integer(1);
Integer b = new Integer(1);
Integer c = 1; //auto box
Integer d = 1; //auto box
map.put(a, "A");
map.put(b, "B");
map.put(c,"C");
map.put(d,"D");
map.size() // size is 3;

祝你好运。

于 2010-07-10T05:43:39.193 回答
3

弱键似乎是一个错误。尝试使用强键,因为它们是整数。

于 2010-07-09T12:23:53.313 回答
0

我想提请您注意 Suppliers.memoizeWithExpirationm,即时缓存。

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Suppliers.html#memoizeWithExpiration(com.google.common.base.Supplier , long, java.util.concurrent.时间单位)

于 2010-08-09T12:39:00.010 回答