HashMap vs. HashTable vs. SyncronizeHashMap vs. ConcurrentHashMap in Java

HashMap
It can lead to inconsistent or unexpected results. This is because HashMap’s operations like getput, and remove are not atomic, meaning that they can be interrupted in the middle of execution.
It's NOT thread-safe, which means that it does NOT provide any built-in synchronization mechanisms to ensure that multiple threads can access and modify the map concurrently without interfering with each other.
1__vc6aYXrIKcqtzd5VBFTOw
NOT thread-safe. Can have one null key and multiple null values.


Hashtable

It is thread-safe by locking the entire map while one thread is making changes to it. This means that only one thread can access or modify the map at a time, which ensures that the map remains in a consistent state.

Iteration methods behaviour: If a thread tries to modify the map while another thread is iterating over it — such as keySet()values(), and entrySet() — , the modifying thread will be blocked until the iteration is complete.

1_iPQvLNsoVtZjNeNcmVRcxw
Thread-safe. Slow Performance because only one thread can work at a time in the entire table. Not allow null key and null values.





SyncronizedMap

It is thread-safe by locking the entire map while one thread is making changes to it.

Iteration methods behaviour: The main difference from Hashtable is that synchronizedMap throws a ConcurrentModificationException if a thread tries to modify the map while another thread is iterating over it using methods — such as keySet()values(), and entrySet().

1_feO-0yky5q2tiELwPKVRcQ
Thread-safe. Slow Performance because only one thread can work at a time in the entire table. Allow null key and null values.



ConcurrentHashMap

It is thread-safe and uses a technique called “lock striping” or “segmentation” to divide the map into multiple segments, each of which is protected by its own lock. One thread that modifies one segment, locks it until it's finished, while other threads that need to modify this same segment will be waiting its release. But in the meantime the other free segments can be modified by other threads.

Weak consistencyConcurrentHashMap has weak consistency, which means that the iteration may reflect some, but not all, of the modifications that were made to the map during iteration. So it allows multiple threads to read from the map simultaneously, without blocking each other. But if there is a writing thread running in the meantime, reading from the map could get “old” or inconsistent values.

1_KKSXVstj5F3W9QzsgqsxOQ
Thread-safe. Fast performance due to “segmentation” strategy. Write operations will lock the segment and block next writings until the segment is released. Read operations will be able to operate freely


Post a Comment

Previous Post Next Post