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.

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); } }

转载于:https://www.cnblogs.com/davidwang456/p/6018203.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值