我想使用 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,为什么我的测试程序没有尽快删除条目?是否可以将引用队列添加到缓存映射?