0
嘗試瞭解ConcurrentWeakKeyHashMap如何響應內存條件/垃圾回收。ConcurrentWeakKeyHashMap大小()方法
以下代碼在我的JUnit測試中,maxNum == 6000, 斷言語句失敗,大小== 4123(或類似的東西)。
我把我的JVM -Xmx設置爲500m,希望得到6000,但沒有運氣。
假設由於垃圾收集造成的大小變化,弱密鑰得到回收的條件是什麼?即「低內存,低別的東西」的條件?
int maxNum = 6000;
int initalCapacity = 2*maxNum;
ConcurrentMap<String,String> concurrentMap = new ConcurrentWeakKeyHashMap<String,String>(initalCapacity);
int count = 0;
for(int i=0; i<maxNum; i++) {
String key = "k" + i;
String value = "v" + i;
concurrentMap.put(key, value);
count = i;
//System.out.println(concurrentMap.size());
}
int size = concurrentMap.size();
assertEquals(size, maxNum);
System.gc();
size = concurrentMap.size();
assertEquals(size, maxNum);
編輯
通過強大的對象釘扎弱密鑰,我總是得到 6000/MAXNUMBER。 即
// our strong object
List<String> strongList = new ArrayList();
for(int i=0; i<maxNum; i++) {
String key = "k" + i;
String value = "v" + i;
concurrentMap.put(key, value);
// key is now pinned in strong object
strongList.add(key);
}
// size will now equal to maxNum, as nothing gets reclaimed
int size = concurrentMap.size();
好吧,所以它看起來像我不能真正控制哪些條目被回收 – portoalet
是的,你只能控制* * *回收(通過保持另一個引用的地方)。 – Thilo
好吧,當我把鍵放在強對象(ConcurrentHashMap)中時,我得到了6000。謝謝Thilo。 – portoalet