1 행과 2 행을 주석 처리하지 않으면 1 행이 OutOfMemoryError가됩니다. 그 반대의 경우, 키, 값 >이 WeakReference에 래핑되기 때문에 OutOfMemoryError가 발생하지 않습니다. 그러나 나는 3 호선의 출력을 이해할 수 없다. - i : 3869 Size : 3870 maxSize : 3870
. 자바 문서에서Java에서 맵 크기가 잘못되었습니다. WeakReference에서 키와 값을 래핑 한 다음 HashMap에 추가하면 인쇄 된 크기가 예상보다 다릅니다
:
가비지 컬렉터는 언제라도 키를 폐기 할 수 있기 때문에 알 수없는 스레드가 자동으로 항목을 제거하고 그래도 같이의 WeakHashMap가 작동 할 수 있습니다.
이 문구 크기는 줄여야하지만 줄 3 출력은 계속 증가하는 것으로 보입니다. 왜 그렇게?
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class WrongWeakHashMapSize {
private static Map map = new HashMap();
public static void main(String[] args) {
for (int i = 0, maxSize = 0; i < 10000000L; ++i) {
/*
* Line 1 Causes java.lang.OutOfMemoryError: Java heap space Error.
* After this line i : 244 Size : 490 maxSize : 490.
*/
map.put(new LargeObject(i), new Integer(i)); // Line 1
/* After Commenting Line 1 :----
* Line 2 Does not Cause java.lang.OutOfMemoryError. Because of WeakReference class use.I think Line 3
* is showing wrong Size of MAP. it printed
* i : 3869 Size : 3870 maxSize : 3870 which seems almost impossible
* because 3870 objects of LargeObject can not be exist at a time.
*/
map.put(new WeakReference(new LargeObject(i)), new WeakReference(new Integer(i))); // Line 2
maxSize = maxSize < map.size() ? map.size() : maxSize; // Line 3
System.out.println("i : " + i + " Size : " + map.size() + " maxSize : " + maxSize); // Line 4
}
}
public static class LargeObject {
private final byte[] space = new byte[1024 * 1024];
private final int id;
public LargeObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
}
WeakHashMap을 사용하지 않고 일반적인 'HashMap'을 사용합니다. 왜 WeakHashMap의 동작을 기대합니까? –
@MarkRotteveel 퍼포먼스의 차이를보고 싶습니다.이 구현을 사용하면 어떤 차이가 있는지 알고 싶습니다. – HakunaMatata