HashMap是传统集合下的类,ConcurrentHashMap是并发集合下的类。除此之外,它们之间还有各种不同之处:
区别
- HashMap本质上是非同步的,即HashMap不是线程安全的,而ConcurrentHashMap是线程安全的。
- HashMap性能比较高,因为它是非同步的,任意数量的线程都可以同时访问它。而ConcurrentHashMap性能比较低,因为有时候线程需要在ConcurrentHashMap上等待请求。
- 当一个线程正在迭代HashMap时,如果有另外一个线程试图对这个HashMap的元素进行新增或者修改,我们将得到运行时异常 ConcurrentModificationException。然而,我们在迭代ConcurrentHashMap时执行任何修改都不会出现任何异常。
- HashMap的key和value可以为null,ConcurrentHashMap不允许,否则会报运行时异常NullPointerException。
- HashMap 是在 JDK 1.2 中引入的,而 ConcurrentHashMap 是由 SUN Microsystem 在 JDK 1.5 中引入的。
实例演示
线程安全
HashMap 示例
public class HashMapTest extends Thread {
static Map<Integer,String> l = new HashMap<Integer,String>();
@Override
public void run() {
try {
Thread.sleep(1000);
// Child thread trying to add
// new element in the object
l.put(103,"D");
} catch(InterruptedException e) {
System.out.println("Child Thread going to add element");
}
}
public static void main(String[] args) throws InterruptedException {
l.put(100,"A");
l.put(101,"B");
l.put(102,"C");
HashMapTest t = new HashMapTest();
t.start();
for (Object o : l.entrySet()) {
System.out.println(o);
Thread.sleep(1000);
}
System.out.println(l);
}
}
输出:
Exception in thread "main" java.util.ConcurrentModificationException
ConcurrentHashMap 示例
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapTest extends Thread {
static ConcurrentHashMap<Integer,String> l = new ConcurrentHashMap<Integer,String>();
@Override
public void run() {
l.put(103,"D");
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
System.out.println("Child Thread going to add element");
}
}
public static void main(String[] args) throws InterruptedException {
l.put(100,"A");
l.put(101,"B");
l.put(102,"C");
ConcurrentHashMapTest t = new ConcurrentHashMapTest();
t.start();
for (Object o : l.entrySet()) {
System.out.println(o);
Thread.sleep(1000);
}
System.out.println(l);
}
}
输出:
100=A
101=B
102=C
103=D
{100=A, 101=B, 102=C, 103=D}
是否允许null
HashMap 示例
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
Map map = new HashMap();
map.put("name", "zhangsan");
map.put(null, "tom");
map.put("address", null);
map.put(null, null);
System.out.println(map.toString());
}
}
输出:
{null=null, address=null, name=zhangsan}
ConcurrentHashMap 示例
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapTest {
public static void main(String[] args) {
ConcurrentHashMap map = new ConcurrentHashMap();
map.put("name", "zhangsan");
map.put(null, "tom");
map.put("address", null);
map.put(null, null);
System.out.println(map.toString());
}
}
输出:
Exception in thread "main" java.lang.NullPointerException