完整GC期间是否会清除WeakHashMap? [英] Are WeakHashMap cleared during a full GC?

查看:71
本文介绍了完整GC期间是否会清除WeakHashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WeakHashMap上遇到了一些麻烦.

I encountered some troubles with WeakHashMap.

请考虑以下示例代码:

List<byte[]> list = new ArrayList<byte[]>();

Map<String, Calendar> map = new WeakHashMap<String, Calendar>();
String anObject = new String("string 1");
String anOtherObject = new String("string 2");

map.put(anObject, Calendar.getInstance());
map.put(anOtherObject, Calendar.getInstance());
// In order to test if the weakHashMap works, i remove the StrongReference in this object
anObject = null;
int i = 0;
while (map.size() == 2) {
   byte[] tab = new byte[10000];
   System.out.println("iteration " + i++ + "map size :" + map.size());
   list.add(tab);
}
System.out.println("Map size " + map.size());

此代码有效.在循环内部,我正在创建对象.当发生次要GC时,在第1360次迭代中映射大小等于1.一切都好.

This code works. Inside the loops, i'm creating object.When a minor GC occurs, the map size is equal to 1 at the 1360th iteration. All is OK.

现在,当我评论此行时:

Now when i comment this line:

//anObject = null; 

我期望有一个OutOfMemoryError,因为mapSize始终等于2.但是在第26XXX次迭代中,会发生完整的GC,并且映射大小等于0.我不明白为什么?

I expect to have an OutOfMemoryError because the mapSize is always equal to 2. However at the 26XXX th iteration, a full GC occurs and the map size is equal to 0. I dont understand why?

我认为不应该清除地图,因为这两个对象也有很强的引用.

I thought that the map shouldn't have cleared because there are also strong references to both objects.

推荐答案

即时编译器分析代码,发现循环后未使用anObjectanOtherObject,并将其从本地删除.变量表或将其设置为null,而循环仍在运行.这称为OSR编译.

The just-in-time compiler analyzes the code, sees that anObject and anOtherObject are not used after the loop, and removes them from the local variable table or sets them to null, while the loop is still running. This is called OSR compilation.

稍后,GC会收集字符串,因为不再保留对字符串的强引用.

Later the GC collects the strings because no strong references to them remain.

如果在循环后使用anObject,您仍然会得到OutOfMemoryError.

If you used anObject after the loop you'd still get an OutOfMemoryError.

更新:您将找到有关 OSR编译.

这篇关于完整GC期间是否会清除WeakHashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆