原文地址: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. sqlplus运行sql文件

    当sql文件的数据比较多的时候,pl/sql运行比较慢,可以通过oracle的sqlplus进行导入: sqlplus user/password@tnsname@sqlfile.sql; 注意如果文 ...

  2. mysql 数据表中查找重复记录

    select mobile_phone,count(*) as count from lawyer group by mobile_phone having count>1;

  3. centos 格式化分区

    #格式化U盘,成fat32 fdisk -l #获取U盘设备信息 #Disk /dev/sdc: 16.0 GB, 16025387008 bytes, 31299584 sectors#Units ...

  4. 远程桌面连接 win7 主机提示“您的凭据不工作”的解决办法

    搞了大半天,找了百度N中方式操作,至少翻看10种以上解决方式,结果还是不得行 索性使用了360搜索,搜了几次就搞定了. 解决办法: “ 最重要一点, 主机上要允许用户以非guest身份登录:主机上运行 ...

  5. sql SYS对象集合

    select * from SYS.objects select * from SYS.all_objects select * from SYS.tables select * from SYS.c ...

  6. 关于OpenStack的学习路线及相关资源汇总

    首先我们想学习openstack,那么openstack是什么?能干什么?涉及的初衷是什么?由什么来组成?刚接触openstack,说openstack不是一个软件,而是由多个组件进行组合,这是一个更 ...

  7. PreparedStatement的应用

    package it.cast.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql ...

  8. Linux堆溢出漏洞利用之unlink

    Linux堆溢出漏洞利用之unlink 作者:走位@阿里聚安全 0 前言 之前我们深入了解了glibc malloc的运行机制(文章链接请看文末▼),下面就让我们开始真正的堆溢出漏洞利用学习吧.说实话 ...

  9. mysql字符串处理例子

    项目中用到的,要判断表中某个字段的某几位,若为某个值则替换,用到了几个典型的字符串操作,记录备注实现方案如下: 备注:如果替代字符串是唯一的话,可以用replace,这里用的是concat拼接. DE ...

  10. AngularJS 中的Promise --- $q服务详解

    先说说什么是Promise,什么是$q吧.Promise是一种异步处理模式,有很多的实现方式,比如著名的Kris Kwal's Q还有JQuery的Deffered. 什么是Promise 以前了解过 ...