Java ConcurrentHashMap
Sample ConcurrentHashMap
The ConcurrentHashMap class in Java is a thread-safe implementation of the Map interface. This means it allows multiple threads to access and modify its contents concurrently without throwing ConcurrentModificationException errors.
Here are some key points about ConcurrentHashMap:
Without concurrent ConcurrentHashMap, we will get exception
java.util.ConcurrentModificationException
public class ConcurrentHashMapSample {
public static void main(String[] args) {
Map<String, Object> animals = new HashMap<String, Object>();
animals.put("penguin", 1);
animals.put("flamingo", 2);
animals.put("tiger", 3);
for(Map.Entry<String, Object> entry: animals.entrySet()) {
if (entry.getKey().equals("tiger")) {
animals.remove("tiger");
}
}
for(Map.Entry<String, Object> entry: animals.entrySet()) {
System.out.println("==key:"+entry.getKey());
}
}
}
With ConcurrentHashMap
领英推荐
public class ConcurrentHashMapSample {
public static void main(String[] args) {
Map<String, Object> animals = new ConcurrentHashMap<>();
animals.put("penguin", 1);
animals.put("flamingo", 2);
animals.put("tiger", 3);
for(Map.Entry<String, Object> entry: animals.entrySet()) {
if (entry.getKey().equals("tiger")) {
animals.remove("tiger");
}
}
for(Map.Entry<String, Object> entry: animals.entrySet()) {
System.out.println("==key:"+entry.getKey());
}
}
}
The code run success and we get the result
==key:penguin
==key:flamingo
--end