對WeakHashMap的使用不慎導致記憶體溢位分析
阿新 • • 發佈:2019-01-02
public class Locker {
private static WeakHashMap<String, Locker> lockerMap = new WeakHashMap<String, Locker>();
private final String id;
private Locker(String id) {
this.id= id;
}
public synchronized static Locker acquire(String id) {
Locker locker = lockerMap.get(key);
if (locker == null) {
locker = new Locker(id);
lockerMap.put(id, locker); //問題程式碼,導致了entry.key ==
entry.value.id
//lockerMap.put(new String(id), locker);
//這是一種修改方式,保證了WeakHashMap中的key,沒有被value直接或間接所引用
}
return locker;
}
public String getId() {
return this.id;
}
public static int getSize() {
return lockerMap.size();
}
}
public class LockerTest extends TestCase {
public void testLocker() {
for (int i = 0; i < 10000000; i++) {
Locker.acquire("abc" + i);
if (i % 10000 == 0) {
System.gc();
System.out.println(Locker.getSize()); //輸出垃圾回收後的Map的Size
}
}
}
}