Searching...
Tuesday, 13 August 2013

ThreadSafe HashMap (ConcurrentHashMap) Example

05:33

ConcurrentHashMap documentation

Concurrent HashMap is thread safe part of java concurrent api, see more about ConcurrentHashMap

Example

In this example two threads are using same map and see how it is behaving with ConcurrentHashMap

package com.vinod.collections;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentHashMapExample implements Runnable{
    private String threadname;
    private static Map<String, String> cmap = new ConcurrentHashMap<String, String>();
    ConcurrentHashMapExample(String threadname) {
        this.threadname = threadname;
        cmap.put(threadname, threadname);
    }

    public void run() {
        try {
            Iterator<String> it = cmap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                cmap.put(key + 1, threadname);
            }
            System.out.println(threadname + "Data inserted");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(new ConcurrentHashMapExample("Student"));
        executor.execute(new ConcurrentHashMapExample("Employee"));
        for (Entry<String, String> entry : cmap.entrySet()) {
            System.out.println("Key " + entry.getKey() + " Value "
                    + entry.getValue());
        }
        executor.shutdownNow();
    }

}
  

Output

StudentData inserted
EmployeeData inserted
Key Student1 Value Employee
Key Employee1 Value Employee
Key Student11 Value Employee
Key Student Value Student
Key Employee Value Employee

If we are using HashMap instead of ConcurrentHashMap we will get below error


StudentData inserted
Key Student Value Student
Key Employee1 Value Employee
Key Employee Value Employee
Key Student1 Value Employee
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at com.vinod.ConcurrentHashMapExample.run(ConcurrentHashMapExample.java:25)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:680)

 

0 comments: