Tuve algunos problemas con WeakHashMap.¿WeakHashMap se borra durante un GC completo?
consideran este código de ejemplo:
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());
Este código funciona. Dentro de los bucles, estoy creando un objeto. Cuando se produce un GC menor, el tamaño del mapa es igual a 1 en la 1360.a iteración. Todo está bien.
Ahora cuando comento esta línea:
//anObject = null;
espero tener un OutOfMemoryError porque el mapSize es siempre igual a 2. Sin embargo en la iteración º 26XXX, un GC completa ocurre y el tamaño del mapa es igual a 0. No entiendo por qué?
Pensé que el mapa no debería haberse borrado porque también hay fuertes referencias a ambos objetos.
Creo que su prueba no es correcta. Si cambia 'while (map.size() == 2) {' to 'while (map.size()> 0) {', las dos pruebas finalizarán hasta que el mapa esté vacío, sin importar que usted comente 'anObject = null' o no. Por cierto, ya lo intenté. – donnior
Imprime 'anObject' y' anOtherObject' al final. El compilador ve que ya no los está usando y puede eliminarlos antes. –