原文地址:http://www.concretepage.com/java/example_concurrenthashmap_java

On this page we will provide example of ConcurrentHashMap in java. ConcurrentHashMap is thread safe but does not use locking on complete map. It is fast and has better performance in comparison to Hashtable in concurrent environment. Find some methods of ConcurrentHashMap.

get() : Pass the key as an argument and it will return associated value. 
put(): Pass key and value and it will map. 
putIfAbsent(): Pass key and value and it will map only if key is not already present. 
remove(): Removes the entry for the given key.

Java ConcurrentHashMap Internal Working

1. Concurrency for retrieval: Retrieval of elements from ConcurrentHashMap does not use locking. It may overlap with update operation. We get the elements of last successfully completed update operation. In case of aggregate operations such as putAll and clear(), concurrent retrieval may show insertion or removal of only some elements.

2. Iteration of ConcurrentHashMap: Iterators and Enumerations also return the elements which have been concurrently added while iterating. ConcurrentHashMap does not throw ConcurrentModificationException.

3. Concurrency for updates: Concurrent updates are thread safe. ConcurrentHashMap constructor has an optional concurrency level argument. The default value is 16. This is the estimated number of concurrently updating threads. It is used in internal sizing to accommodate concurrently updating threads. Hash table is internally partitioned into the concurrency level number so that it can avoid updating concurrent thread contention.

 

ConcurrentHashMap Example

Find the example. 
ConcurrentHashMapDemo.java

package com.concretepage;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentHashMapDemo {
private final ConcurrentHashMap<Integer,String> conHashMap = new ConcurrentHashMap<Integer,String>();
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
ConcurrentHashMapDemo ob = new ConcurrentHashMapDemo();
service.execute(ob.new WriteThreasOne());
service.execute(ob.new WriteThreasTwo());
service.execute(ob.new ReadThread());
service.shutdownNow();
}
class WriteThreasOne implements Runnable {
@Override
public void run() {
for(int i= 1; i<=10; i++) {
conHashMap.putIfAbsent(i, "A"+ i);
}
}
}
class WriteThreasTwo implements Runnable {
@Override
public void run() {
for(int i= 1; i<=5; i++) {
conHashMap.put(i, "B"+ i);
}
}
}
class ReadThread implements Runnable {
@Override
public void run() {
Iterator<Integer> ite = conHashMap.keySet().iterator();
while(ite.hasNext()){
Integer key = ite.next();
System.out.println(key+" : " + conHashMap.get(key));
}
}
}
}

Output

1 : B1
2 : B2
3 : B3
4 : B4
5 : B5
6 : A6
7 : A7
8 : A8
9 : A9
10 : A10

ConcurrentHashMap vs Hashtable

1. ConcurrentHashMap is based on hash table. It allows to put null object but Hashtable allows only not-null object.

2. The object which is being used as key must override hashCode() and equals() methods. 
3. The methods such as get()put()remove() are synchronized in Hashtable whereas ConcurrentHashMap does not use synchronized methods for concurrency.

4. In concurrent modification, the iteration of Hashtable elements will throw ConcurrentModificationException whereasConcurrentHashMap does not.

ConcurrentHashMap vs HashMap

1. ConcurrentHashMap and HashMap both are based on hash table.

2. ConcurrentHashMap supports full concurrency of retrieval. HashMap can be synchronized usingCollections.synchronizedMap() .

3. ConcurrentHashMap provides concurrency level for updates that can be changed while instantiating.

4. In concurrent modification HashMap throws ConcurrentModificationException whereas ConcurrentHashMap does not.

Example of ConcurrentHashMap in Java--转的更多相关文章

  1. Java ConcurrentHashMap (Java代码实战-005)

    package Threads; import com.google.common.collect.Maps; import java.util.concurrent.ConcurrentMap; i ...

  2. 为并发而生的 ConcurrentHashMap(Java 8)

    HashMap 是我们日常最常见的一种容器,它以键值对的形式完成对数据的存储,但众所周知,它在高并发的情境下是不安全的.尤其是在 jdk 1.8 之前,rehash 的过程中采用头插法转移结点,高并发 ...

  3. 从ConcurrentHashMap的演进看Java多线程核心技术 Java进阶(六)

    本文分析了HashMap的实现原理,以及resize可能引起死循环和Fast-fail等线程不安全行为.同时结合源码从数据结构,寻址方式,同步方式,计算size等角度分析了JDK 1.7和JDK 1. ...

  4. Java并发包--ConcurrentHashMap原理解析

    ConcurrentHashMap实现原理及源码分析   ConcurrentHashMap是Java并发包中提供的一个线程安全且高效的HashMap实现(若对HashMap的实现原理还不甚了解,可参 ...

  5. Java多线程_并发容器ConcurrentHashMap/CopyOnWriteArrayList/CopyOnWriteArraySet

    ConcurrentHashMap         HashMap是线程不安全的,可以使用Collections.synchronizedMap(map)把一个不安全的map变成安全的,但是这里可以直 ...

  6. Java:ConcurrentHashMap类小记-1(概述)

    Java:ConcurrentHashMap类小记-1(概述) 对 Java 中的 ConcurrentHashMap类,做一个微不足道的小小小小记,分三篇博客: Java:ConcurrentHas ...

  7. java多线程--同步屏障CyclicBarrier的使用

    CyclicBarrier的概念理解: CyclicBarrier的字面上的意思是可循环的屏障,是java并发包java.util.concurrent 里的一个同步工具类,在我下载的JDK1.6的中 ...

  8. Java多线程系列目录(共43篇)

    最近,在研究Java多线程的内容目录,将其内容逐步整理并发布. (一) 基础篇 01. Java多线程系列--“基础篇”01之 基本概念 02. Java多线程系列--“基础篇”02之 常用的实现多线 ...

  9. 【JUC】JDK1.8源码分析之ConcurrentHashMap(一)

    一.前言 最近几天忙着做点别的东西,今天终于有时间分析源码了,看源码感觉很爽,并且发现ConcurrentHashMap在JDK1.8版本与之前的版本在并发控制上存在很大的差别,很有必要进行认真的分析 ...

随机推荐

  1. PHP 之 CURL 模拟登陆并获取数据

    1.CURL模拟登陆的流程和步骤 2.tempnam 创建一个临时文件 3.使用CURL模拟登陆到PHP100论坛 <?php $cookie_file = tempnam('./temp',' ...

  2. css中单位px、pt、em和rem的区别

    国内的设计师大都喜欢用px,而国外的网站大都喜欢用em和rem,那么三者有什么区别,又各自有什么优劣呢? px :像素(Pixel).相对长度单位.像素px是相对于显示器屏幕分辨率而言的.(引自CSS ...

  3. @autowired和@resource的区别

    @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自 动注入罢了.@Resource有两个属性是比较重要的, ...

  4. DSY1531*Bank notes

    Description Byteotian Bit Bank (BBB) 拥有一套先进的货币系统,这个系统一共有n种面值的硬币,面值分别为b1, b2,..., bn. 但是每种硬币有数量限制,现在我 ...

  5. LA

    grmon -altjtag -u 公式rand()%(b-a),是求范围随机数的计算公式,%是做求余运算,正整数对n求余的范围肯定是在0~n-1之间,也就是rand()%(b-a)的范围是0~b-a ...

  6. gulp es7配置文件

    http://sanwen.net/a/ybsfcoo.html /** * Created by udi on 2016/11/24. */ var gulp = require('gulp'); ...

  7. Redis系列(四)-低成本高可用方案设计

    关于Redis高可用方案,看到较多的是keepalived.zookeeper方案. keepalived是主备模式,意味着总有一台浪费着.zookeeper工作量成本偏高. 本文主要介绍下使用官方s ...

  8. Three.js + HTML5 Audio API 打造3D音乐频谱,Let’s ROCK!

    继续玩味之前写的音乐频谱作品,将原来在Canvas标签上的 作图利用Three.js让它通过WebGL呈现,这样就打造出了一个全立体感的频谱效果了. 项目详情及源码 项目GitHub地址:https: ...

  9. Java 浅析内部类

    这篇文章主要讲述Java 内部类的相关知识,主要讲解下面的知识点. 内部类的概念 内部类的特点与使用 多种形式内部类 为什么要使用内部类 内部类的概念 内部类是指在一个类的内部定义了另一个类.例如下面 ...

  10. WebApi系列~目录

    回到占占推荐博客索引 写了这个系列的文章不少了,也应该为大家写个目录了,最近很刮了很多SOA的风,很多企业都将自己的系统进行分割,通常是按模块进行拆分,为这个模块提供统一的接口提供业务服务,这不紧可以 ...