Java中并发哈希映射和同步哈希映射之间的区别
并发Hashmap是jdk1.5中引入的类。并发哈希映射仅在添加或更新映射时在称为片段的存储桶级别应用锁。因此,并发哈希映射允许对映射进行并发读写操作。
同步hashmap(Collection.syncronizedHashMap())是Collection框架的一种方法。此方法将锁应用于整个集合。因此,如果一个线程正在访问该映射,则没有其他线程可以访问同一映射。
SynchronizedMap的示例
public class SynchronizedMapExample {
public static void main(String[] args) {
Map<Integer,String> laptopmap = new HashMap<Integer,String>();
laptopmap.put(1,"IBM");
laptopmap.put(2,"Dell");
laptopmap.put(3,"HCL");
//创建一个同步映射
Map<Integer,String> syncmap = Collections.synchronizedMap(laptopmap);
System.out.println("Synchronized map is : "+syncmap);
}
}ConcurrentHashMap---的示例
public class ConcurrentHashMap---Example {
public static void main(String[] args) {
//ConcurrentHashMap---
Map<Integer,String> laptopmap = new ConcurrentHashMap---<Integer,String>();
laptopmap.put(1,"IBM");
laptopmap.put(2,"Dell");
laptopmap.put(3,"HCL");
System.out.println("ConcurrentHashMap--- is: "+laptopmap);
}
}