Source From Here
Preface
HashMap is a very powerful data structure in Java. We use it everyday and almost in all applications. There are quite a few examples which I have written before on How to Implement Threadsafe cache, How to convert HashMap to Arraylist? We used HashMap in both below examples but those are pretty simple use cases of HashMap. HashMap is a non-synchronized collection class.
Do you have any of below questions?
In this tutorial we will go over all above queries and reason why and how we could Synchronize Hashmap?
Why?
The Map object is an associative containers that store elements, formed by a combination of a uniquely identify key and a mapped value. If you have very highly concurrent application in which you may want to modify or read key value in different threads then it’s ideal to use Concurrent Hashmap. Best example is Producer Consumer which handles concurrent read/write.
So what does the thread-safe Map means? If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally to avoid an inconsistent view of the contents.
How?
There are two ways we could synchronized HashMap:
- HashMap Vs. synchronizedMap Vs. ConcurrentHashMap
ConcurrentHashMap
SynchronizedHashMap
Now let’s take a look at code
1. Create class CrunchifyConcurrentHashMapVsSynchronizedHashMap.java
2. Create object for each HashMap, SynchronizedMap and ConcurrentHashMap
3. Add and retrieve 500k entries from Map
4. Measure start and end time and display time in milliseconds
5. We will use ExecutorService to run 5 threads in parallel
- CrunchifyConcurrentHashMapVsSynchronizedMap.java
One possible execution result:
Preface
HashMap is a very powerful data structure in Java. We use it everyday and almost in all applications. There are quite a few examples which I have written before on How to Implement Threadsafe cache, How to convert HashMap to Arraylist? We used HashMap in both below examples but those are pretty simple use cases of HashMap. HashMap is a non-synchronized collection class.
Do you have any of below questions?
In this tutorial we will go over all above queries and reason why and how we could Synchronize Hashmap?
Why?
The Map object is an associative containers that store elements, formed by a combination of a uniquely identify key and a mapped value. If you have very highly concurrent application in which you may want to modify or read key value in different threads then it’s ideal to use Concurrent Hashmap. Best example is Producer Consumer which handles concurrent read/write.
So what does the thread-safe Map means? If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally to avoid an inconsistent view of the contents.
How?
There are two ways we could synchronized HashMap:
- HashMap Vs. synchronizedMap Vs. ConcurrentHashMap
- //Hashtable
- Map
normalMap = new Hashtable (); - //synchronizedMap
- synchronizedHashMap = Collections.synchronizedMap(new HashMap
()); - //ConcurrentHashMap
- concurrentHashMap = new ConcurrentHashMap
();
SynchronizedHashMap
Now let’s take a look at code
1. Create class CrunchifyConcurrentHashMapVsSynchronizedHashMap.java
2. Create object for each HashMap, SynchronizedMap and ConcurrentHashMap
3. Add and retrieve 500k entries from Map
4. Measure start and end time and display time in milliseconds
5. We will use ExecutorService to run 5 threads in parallel
- CrunchifyConcurrentHashMapVsSynchronizedMap.java
- 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
crunchifyHashTableObject = null; - public static Map
crunchifySynchronizedMapObject = null; - public static Map
crunchifyConcurrentHashMapObject = null; - public static void main(String[] args) throws InterruptedException {
- // Test with Hashtable Object
- crunchifyHashTableObject = new Hashtable
(); - crunchifyPerformTest(crunchifyHashTableObject);
- // Test with synchronizedMap Object
- crunchifySynchronizedMapObject = Collections.synchronizedMap(new HashMap
()); - crunchifyPerformTest(crunchifySynchronizedMapObject);
- // Test with ConcurrentHashMap Object
- crunchifyConcurrentHashMapObject = new ConcurrentHashMap
(); - crunchifyPerformTest(crunchifyConcurrentHashMapObject);
- }
- public static void crunchifyPerformTest(final Map
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);
- }
- }
- });
- }
- // Make sure executor stops
- crunchifyExServer.shutdown();
- // Blocks until all tasks have completed execution after a shutdown request
- crunchifyExServer.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
- long entTime = System.nanoTime();
- long totalTime = (entTime - startTime) / 1000000L;
- averageTime += totalTime;
- System.out.println("2500K entried added/retrieved in " + totalTime + " ms");
- }
- System.out.println("For " + crunchifyThreads.getClass() + " the average time is " + averageTime / 5 + " ms\n");
- }
- }
This message was edited 10 times. Last update was at 30/11/2016 20:59:38
沒有留言:
張貼留言