Example of ConcurrentHashMap in Java--转
原文地址: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.
Contents
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--转的更多相关文章
- Java ConcurrentHashMap (Java代码实战-005)
package Threads; import com.google.common.collect.Maps; import java.util.concurrent.ConcurrentMap; i ...
- 为并发而生的 ConcurrentHashMap(Java 8)
HashMap 是我们日常最常见的一种容器,它以键值对的形式完成对数据的存储,但众所周知,它在高并发的情境下是不安全的.尤其是在 jdk 1.8 之前,rehash 的过程中采用头插法转移结点,高并发 ...
- 从ConcurrentHashMap的演进看Java多线程核心技术 Java进阶(六)
本文分析了HashMap的实现原理,以及resize可能引起死循环和Fast-fail等线程不安全行为.同时结合源码从数据结构,寻址方式,同步方式,计算size等角度分析了JDK 1.7和JDK 1. ...
- Java并发包--ConcurrentHashMap原理解析
ConcurrentHashMap实现原理及源码分析 ConcurrentHashMap是Java并发包中提供的一个线程安全且高效的HashMap实现(若对HashMap的实现原理还不甚了解,可参 ...
- Java多线程_并发容器ConcurrentHashMap/CopyOnWriteArrayList/CopyOnWriteArraySet
ConcurrentHashMap HashMap是线程不安全的,可以使用Collections.synchronizedMap(map)把一个不安全的map变成安全的,但是这里可以直 ...
- Java:ConcurrentHashMap类小记-1(概述)
Java:ConcurrentHashMap类小记-1(概述) 对 Java 中的 ConcurrentHashMap类,做一个微不足道的小小小小记,分三篇博客: Java:ConcurrentHas ...
- java多线程--同步屏障CyclicBarrier的使用
CyclicBarrier的概念理解: CyclicBarrier的字面上的意思是可循环的屏障,是java并发包java.util.concurrent 里的一个同步工具类,在我下载的JDK1.6的中 ...
- Java多线程系列目录(共43篇)
最近,在研究Java多线程的内容目录,将其内容逐步整理并发布. (一) 基础篇 01. Java多线程系列--“基础篇”01之 基本概念 02. Java多线程系列--“基础篇”02之 常用的实现多线 ...
- 【JUC】JDK1.8源码分析之ConcurrentHashMap(一)
一.前言 最近几天忙着做点别的东西,今天终于有时间分析源码了,看源码感觉很爽,并且发现ConcurrentHashMap在JDK1.8版本与之前的版本在并发控制上存在很大的差别,很有必要进行认真的分析 ...
随机推荐
- 利用ajax的方式来提交数据到后台数据库及交互功能
怎么样用ajax来提交数据到后台数据库,并完成交互呢????? 一.当我们在验证表单的时候,为了阻止把错误的也发送到服务器,我们通常这样设置: $(function(){ var ...
- ubuntu下出现的问题-控制台更新源失败
Ubuntu下控制台输入sudo apt-get update之后出现的问题:E: Could not get lock /var/lib/apt/lists/lock - open (11: Res ...
- 修复jLink V9固件小记
网上买了个山寨jLink V9.3 plus,号称不掉固件的,不过固件最终还是掉了,现象是:插上去红灯亮,发现jLink但是驱动无法安装.估计是固件丢失了,放G搜了一圈发现修复固件都是V8的,但是倒找 ...
- Python之路第一课Day10--随堂笔记(异步IO\数据库\队列\缓存)
本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitMQ队列 Redis\Memcached缓存 Paramiko SS ...
- mysql不能插入中文
mysql不能插入中文 解决办法: 1.打开终端,连接数据库 mysql -u root -p; 2.输入 satus; 查看状态 3.输入 set char set 'gbk'; 4.如果是已有的 ...
- *HDU 1237 栈
简单计算器 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submi ...
- java 过滤器Filter
一.首先在web.xml里进行拦截过滤 <filter> <filter-name>platformServiceAgreementFilter</filt ...
- Python swapcase()方法
首先,要明白Python swapcase() 方法用于对字符串的大小写字母进行转换. 其次,了解swapcase()方法语法:str.swapcase() 返回值:返回大小写字母转换后生成的新字符串 ...
- 反向输出及sort排序
建立条件:#include "algorithm"引用这个头文件 1.reverse 的用法,反向排序,由自己输入5个数: 1 2 3 4 5 for (int i = 0; i ...
- 安装 Linux 时碰到的硬盘分区的陷阱及应对
硬盘分区的陷阱及应对 之所以想到写这篇,是因为本人在折腾 Linux 系统的过程中,有多次掉入硬盘分区的陷阱的经历.最近几天,再一次掉入坑中,折腾了两天才从坑中爬出来.经过多方查询资料,终于弄明白了硬 ...