HashMap vs. ConcurrentHashMap vs. SynchronizedMap: cómo se puede sincronizar un HashMap en Java
Publicado: 2015-01-29
HashMap
es una estructura de datos muy poderosa en Java. Lo usamos todos los días y en casi todas las aplicaciones. Hay bastantes ejemplos que he escrito antes sobre Cómo implementar el caché Threadsafe, ¿Cómo convertir Hashmap a Arraylist?
Usamos Hashmap en los dos ejemplos anteriores, pero esos son casos de uso bastante simples de Hashmap. HashMap is a non-synchronized
.
¿Tiene alguna de las siguientes preguntas?
- ¿Cuál es la diferencia entre ConcurrentHashMap y Collections.synchronizedMap(Map)?
- ¿Cuál es la diferencia entre ConcurrentHashMap y Collections.synchronizedMap(Map) en términos de rendimiento?
- ConcurrentHashMap vs Collections.synchronizedMap()
- Preguntas de entrevista populares de HashMap y ConcurrentHashMap
En este tutorial repasaremos todas las consultas anteriores y por why and how
podríamos sincronizar Hashmap.
¿Por qué?
El objeto Map es un contenedor asociativo que almacena elementos, formado por una combinación de una key
de identificación única y un value
mapeado. Si tiene una aplicación muy concurrente en la que puede querer modificar o leer el valor clave en diferentes subprocesos, entonces es ideal usar Hashmap concurrente. El mejor ejemplo es Producer Consumer, que maneja la lectura/escritura simultánea.
Entonces, ¿qué significa el mapa seguro para subprocesos? Si multiple threads
acceden a un mapa hash al mismo tiempo y al menos uno de los subprocesos modifica el mapa estructuralmente, must be synchronized externally
para evitar una vista inconsistente de los contenidos.
¿Cómo?
Hay dos formas en que podríamos sincronizar HashMap
- Método Java CollectionssynchronedMap()
- Usar ConcurrentHashMap
1 2 3 4 5 6 7 8 |
//Hashtable Map < String , String > normalMap = new Hashtable < String , String > ( ) ; //synchronizedMap synchronizedHashMap = Collections . synchronizedMap ( new HashMap < String , String > ( ) ) ; //ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap < String , String > ( ) ; |
ConcurrentHashMapConcurrentHashMap
- Debe usar ConcurrentHashMap cuando necesite una simultaneidad muy alta en su proyecto.
- Es seguro para subprocesos sin sincronizar
whole map
. - Las lecturas pueden ocurrir muy rápido mientras que la escritura se realiza con un bloqueo.
- No hay bloqueo a nivel de objeto.
- El bloqueo tiene una granularidad mucho más fina a nivel de cubo de hashmap.
- ConcurrentHashMap no lanza una
ConcurrentModificationException
si un subproceso intenta modificarlo mientras otro está iterando sobre él. - ConcurrentHashMap utiliza multitud de bloqueos.
SynchronizedHashMap
- Sincronización a nivel de Objeto.
- Cada operación de lectura/escritura necesita adquirir un bloqueo.
- Bloquear toda la colección es una sobrecarga de rendimiento.
- Básicamente, esto da acceso a un solo hilo a todo el mapa y bloquea todos los demás hilos.
- Puede causar contención.
- SynchronizedHashMap devuelve
Iterator
, que falla rápidamente en la modificación simultánea.
Ahora echemos un vistazo al código.
- Crear clase
CrunchifyConcurrentHashMapVsSynchronizedHashMap.java
- Crear objeto para cada HashTable, SynchronizedMap y CrunchifyConcurrentHashMap
- Agregue y recupere 500k entradas del Mapa
- Mida el tiempo de inicio y finalización y muestre el tiempo en milisegundos
- Usaremos ExecutorService para ejecutar
5 threads
en paralelo
Aquí hay un código Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
package crunchify . com . tutorials ; import java . util . Collections ; import java . util . HashMap ; import java . util . Hashtable ; import java . util . Map ; import java . util . concurrent . ConcurrentHashMap ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . TimeUnit ; /** * @author Crunchify.com * */ public class CrunchifyConcurrentHashMapVsSynchronizedMap { public final static int THREAD_POOL_SIZE = 5 ; public static Map < String , Integer > crunchifyHashTableObject = null ; public static Map < String , Integer > crunchifySynchronizedMapObject = null ; public static Map < String , Integer > crunchifyConcurrentHashMapObject = null ; public static void main ( String [ ] args ) throws InterruptedException { // Test with Hashtable Object crunchifyHashTableObject = new Hashtable < String , Integer > ( ) ; crunchifyPerformTest ( crunchifyHashTableObject ) ; // Test with synchronizedMap Object crunchifySynchronizedMapObject = Collections . synchronizedMap ( new HashMap < String , Integer > ( ) ) ; crunchifyPerformTest ( crunchifySynchronizedMapObject ) ; // Test with ConcurrentHashMap Object crunchifyConcurrentHashMapObject = new ConcurrentHashMap < String , Integer > ( ) ; crunchifyPerformTest ( crunchifyConcurrentHashMapObject ) ; } public static void crunchifyPerformTest ( final Map < String , Integer > crunchifyThreads ) throws InterruptedException { System . out . println ( "Test started for: " + crunchifyThreads . getClass ( ) ) ; long averageTime = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { long startTime = System . nanoTime ( ) ; ExecutorService crunchifyExServer = Executors . newFixedThreadPool ( THREAD_POOL_SIZE ) ; for ( int j = 0 ; j < THREAD_POOL_SIZE ; j ++ ) { crunchifyExServer . execute ( new Runnable ( ) { @SuppressWarnings ( "unused" ) @Override public void run ( ) { for ( int i = 0 ; i < 500000 ; i ++ ) { Integer crunchifyRandomNumber = ( int ) Math . ceil ( Math . random ( ) * 550000 ) ; // Retrieve value. We are not using it anywhere Integer crunchifyValue = crunchifyThreads . get ( String . valueOf ( crunchifyRandomNumber ) ) ; // Put value crunchifyThreads . put ( String . valueOf ( crunchifyRandomNumber ) , crunchifyRandomNumber ) ; } } } ) ; } // Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation // has no additional effect if already shut down. // This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that. crunchifyExServer . shutdown ( ) ; // Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is // interrupted, whichever happens first. crunchifyExServer . awaitTermination ( Long . MAX_VALUE , TimeUnit . DAYS ) ; long entTime = System . nanoTime ( ) ; long totalTime = ( entTime - startTime ) / 1000000L ; averageTime += totalTime ; System . out . println ( "500K entried added/retrieved in " + totalTime + " ms" ) ; } System . out . println ( "For " + crunchifyThreads . getClass ( ) + " the average time is " + averageTime / 5 + " ms\n" ) ; } } |

shutdown()
significa que el servicio ejecutor no toma más tareas entrantes.-
awaitTermination()
se invoca después de una solicitud de apagado.
Y, por lo tanto, primero debe apagar el serviceExecutor y luego bloquear y esperar a que finalicen los subprocesos.
Resultado de la consola de Eclipse:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Test started for: class java.util.Hashtable 500K entried added/retrieved in 1832 ms 500K entried added/retrieved in 1723 ms 500K entried added/retrieved in 1782 ms 500K entried added/retrieved in 1607 ms 500K entried added/retrieved in 1851 ms For class java.util.Hashtable the average time is 1759 ms Test started for: class java.util.Collections$SynchronizedMap 500K entried added/retrieved in 1923 ms 500K entried added/retrieved in 2032 ms 500K entried added/retrieved in 1621 ms 500K entried added/retrieved in 1833 ms 500K entried added/retrieved in 2048 ms For class java.util.Collections$SynchronizedMap the average time is 1891 ms Test started for: class java.util.concurrent.ConcurrentHashMap 500K entried added/retrieved in 1068 ms 500K entried added/retrieved in 1029 ms 500K entried added/retrieved in 1165 ms 500K entried added/retrieved in 840 ms 500K entried added/retrieved in 1017 ms For class java.util.concurrent.ConcurrentHashMap the average time is 1023 ms |