原文地址: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. Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

    去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sS ...

  2. Red Hat5下源码安装mysql5.6过程记录

    1.安装cmake包 [root@edu soft]# tar -xzf cmake-.tar.Z [root@edu soft]# cd cmake- [root@edu cmake-]# ./co ...

  3. CentOS6.5安装中文输入法

    首先进入命令形式的客户端 切换成root用户,输入命令"su root"即可,接着输入 yum install "@Chinese Support" 命令按en ...

  4. java多态性,父类引用指向子类对象

    父类引用指向子类对象指的是: 例如父类Animal,子类Cat,Dog.其中Animal可以是类也可以是接口,Cat和Dog是继承或实现Animal的子类. Animal animal = new C ...

  5. DBImport v3.44 中文版发布:数据库数据互导及文档生成工具(IT人员必备)

    前言: 距离上一个版本V3.3版本的文章发布,已经是1年10个月前的事了. 其实版本一直在更新,但也没什么大的功能更新,总体比较稳定,所以也不怎么写文介绍了. 至于工作上的事,之前有半年时间跑去学英语 ...

  6. .NET面试题系列[14] - LINQ to SQL与IQueryable

    .NET面试题系列目录 名言警句 "理解IQueryable的最简单方式就是,把它看作一个查询,在执行的时候,将会生成结果序列." - Jon Skeet LINQ to Obje ...

  7. Redhat环境下编译安装Google Bazel

    Redhat环境下编译安装bazel 作者:Jack47 目前Google Bazel没有提供各个操作系统下的二进制安装包,只提供源代码,需要我们自己编译安装,详情可以见我翻译的中文版Google B ...

  8. 企业IT管理员IE11升级指南【4】—— IE企业模式介绍

    企业IT管理员IE11升级指南 系列: [1]—— Internet Explorer 11增强保护模式 (EPM) 介绍 [2]—— Internet Explorer 11 对Adobe Flas ...

  9. Linux学习之Exam系统发布

    配置时间:2015年11月27日 配置人:撰写人:微冷的雨   Happy 01.Linux安装图 欢迎页面 桌面 02.Linux命令之文件目录操作 给北大青鸟五道口校区创建三个机房(L4,L5,L ...

  10. 将nuget与VS直接集成,实现一键上传等功能

    nuget是一个非常方便的包管理工具,很多团队为了开发的方便也建立了自己的包源网站(nuget.server),本篇文章是笔者在配置nuget上面的一点小体,其最终目标是要达到能够在VS里一键打包上传 ...