您如何将内存缓存中的弱引用存储到超出缓存大小的对象? 值得吗? 它可以是一个新的内存缓存模式吗? =) 或者我错过了一些已经完成它的库?
这样我们就可以通过id访问对象,即使它们是从内存缓存本身中删除的(如果我们不希望有大内存缓存)。
MemCache来源在这里:http://pastebin.com/N3iuJgNb
示例代码:
Test before1 = new Test("1"); // Strong reference in code, weak reference in MemCache
Test before2 = new Test("2"); // Weak reference in MemCache
Test before3 = new Test("3"); // Strong reference in code and in MemCache
Test before4 = new Test("4"); // Strong reference in MemCache
MemCache<Test> cache = new MemCache<Test>(2); // At most two items are strongly referenced
cache.put(before1.id, before1); // Weak reference
cache.put(before2.id, before2); // Weak reference
cache.put(before3.id, before3); // Strong reference
cache.put(before4.id, before4); // Strong reference
before2 = null;
before4 = null;
System.gc();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Test after1 = cache.get("1"); // LruCache will return null here
Test after2 = cache.get("2");
Test after3 = cache.get("3");
Test after4 = cache.get("4");
assert after1 == before1;
assert after2 == null;
assert after3 == before3;
assert after4 != null;
System.out.println("Success!!!");