HashMap es una clase de colección no sincronizada. Si necesita realizar operaciones seguras para subprocesos en él, debe sincronizarlo explícitamente. En este tutorial veremos cómo sincronizar HashMap
.
Ejemplo:
En este ejemplo tenemos un HashMap
Punto importante a tener en cuenta en el siguiente ejemplo:
El iterador debe usarse en un bloque sincronizado incluso si hemos sincronizado explícitamente el HashMap (como hicimos en el siguiente código).
Sintaxis:
Map map = Collections.synchronizedMap(new HashMap()); ... //This doesn't need to be in synchronized block Set set = map.keySet(); // Synchronizing on map, not on set synchronized (map) { // Iterator must be in synchronized block Iterator iterator = set.iterator(); while (iterator.hasNext()){ ... } }
Código completo:
package beginnersbook.com; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Iterator; public class HashMapSyncExample { public static void main(String args[]) { HashMap<Integer, String> hmap= new HashMap<Integer, String>(); hmap.put(2, "Anil"); hmap.put(44, "Ajit"); hmap.put(1, "Brad"); hmap.put(4, "Sachin"); hmap.put(88, "XYZ"); Map map= Collections.synchronizedMap(hmap); Set set = map.entrySet(); synchronized(map){ Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } } }
Producción:
1: Brad 2: Anil 4: Sachin 88: XYZ 44: Ajit