HashMap vs. ConcurrentHashMap vs. SynchronizedMap – Como um HashMap pode ser sincronizado em Java
Publicados: 2015-01-29
HashMap
é uma estrutura de dados muito poderosa em Java. Nós o usamos todos os dias e quase em todas as aplicações. Existem alguns exemplos que escrevi antes em Como implementar o cache Threadsafe, Como converter Hashmap em Arraylist?
Usamos Hashmap em ambos os exemplos acima, mas esses são casos de uso bastante simples de Hashmap. HashMap is a non-synchronized
.
Você tem alguma das perguntas abaixo?
- Qual é a diferença entre ConcurrentHashMap e Collections.synchronizedMap(Map)?
- Qual é a diferença entre ConcurrentHashMap e Collections.synchronizedMap(Map) em termos de desempenho?
- ConcurrentHashMap vs Collections.synchronizedMap()
- Perguntas populares da entrevista sobre HashMap e ConcurrentHashMap
Neste tutorial, abordaremos todas as consultas acima e why and how
podemos sincronizar o Hashmap?
Por quê?
O objeto Map é um container associativo que armazena elementos, formado por uma combinação de uma key
de identificação exclusiva e um value
mapeado. Se você tem um aplicativo altamente simultâneo no qual pode querer modificar ou ler o valor da chave em diferentes threads, é ideal usar o Hashmap Concorrente. O melhor exemplo é o Producer Consumer, que lida com leitura/gravação simultânea.
Então, o que significa o mapa thread-safe? Se multiple threads
acessarem um mapa de hash simultaneamente e pelo menos um dos encadeamentos modificar o mapa estruturalmente, ele must be synchronized externally
para evitar uma visualização inconsistente do conteúdo.
Quão?
Existem duas maneiras de sincronizar o HashMap
- Método das Coleções Java SynchrodMap()
- 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 > ( ) ; |
ConcurrentHashMap
- Você deve usar ConcurrentHashMap quando precisar de simultaneidade muito alta em seu projeto.
- É thread-safe sem sincronizar
whole map
. - As leituras podem acontecer muito rapidamente enquanto a gravação é feita com um bloqueio.
- Não há bloqueio no nível do objeto.
- O bloqueio está em uma granularidade muito mais fina em um nível de bucket de hashmap.
- ConcurrentHashMap não lança um
ConcurrentModificationException
se um thread tentar modificá-lo enquanto outro estiver iterando sobre ele. - ConcurrentHashMap usa vários bloqueios.
SynchronizedHashMap
- Sincronização em nível de objeto.
- Toda operação de leitura/gravação precisa adquirir bloqueio.
- Bloquear toda a coleção é uma sobrecarga de desempenho.
- Isso essencialmente dá acesso a apenas um thread para todo o mapa e bloqueia todos os outros threads.
- Pode causar contenção.
- SynchronizedHashMap retorna
Iterator
, que falha rapidamente na modificação simultânea.
Agora vamos dar uma olhada no código
- Criar classe
CrunchifyConcurrentHashMapVsSynchronizedHashMap.java
- Criar objeto para cada HashTable, SynchronizedMap e CrunchifyConcurrentHashMap
- Adicione e recupere 500 mil entradas do Mapa
- Meça o tempo de início e término e o tempo de exibição em milissegundos
- Usaremos ExecutorService para executar
5 threads
em paralelo
Aqui está um 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 o serviço executor não recebe mais tarefas.-
awaitTermination()
é invocado após uma solicitação de desligamento.
E, portanto, você precisa primeiro desligar o serviceExecutor e, em seguida, bloquear e aguardar a conclusão dos encadeamentos.
Resultado do Console do 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 |