我将使用基于SoftReference的缓存(一个非常简单的事情).但是,我在为它编写测试时遇到了一个问题.
测试的目的是检查缓存是否在内存清理发生后再次从服务器请求先前缓存的对象.
在这里,我找到了如何使系统释放软引用对象的问题.调用System.gc()是不够的,因为在内存不足之前不会释放软引用.我正在PC上运行此单元测试,因此VM的内存预算可能非常大.
==================后来添加==============================
谢谢所有照顾的人!
考虑到所有职业选手和反对者后,我决定按照nanda和jarnbjo的建议采取蛮力方式.然而,似乎JVM并不是那么愚蠢 - 如果你要求一个比VM的内存预算更大的块,它甚至都不会尝试垃圾收集.所以我修改了这样的代码:
/* Force releasing SoftReferences */
try {
final List<long[]> memhog = new LinkedList<long[]>();
while(true) {
memhog.add(new long[102400]);
}
}
catch(final OutOfMemoryError e) {
/* At this point all SoftReferences have been released - GUARANTEED. */
}
/* continue the test here */
Run Code Online (Sandbox Code Playgroud) 来自jlibs的RuntimeUtil.java 的以下片段保证GC完成垃圾收集.
既然,它也使用System.gc(),我不明白他们怎么能保证它会100%发生.
以下是片段:
/**
* This method guarantees that garbage collection is
* done unlike <code>{@link System#gc()}</code>
*/
public static void gc(){
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
obj = null;
while(ref.get()!=null)
System.gc();
}
Run Code Online (Sandbox Code Playgroud)