zoukankan      html  css  js  c++  java
  • 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);
    			}
    		}
    	  }  
    	  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.

  • 相关阅读:
    View 和 ViewGroup 的 hasFocusable
    tiny4412学习(四)之移植linux-设备树(1)设备树基础知识及GPIO中断【转】
    tiny4412学习(三)之移植linux-4.x驱动(1)支持网卡驱动【转】
    分享tiny4412,emmc烧录u-boot, 支持fastboot模式烧写emmc【转】
    tiny4412学习(一)之从零搭建linux系统(烧写uboot、内核进emmc+uboot启动内核)【转】
    【总结】嵌入式linux内核中Makefile、Kconfig、.config的关系及增加开机Hello World【转】
    tiny4412 裸机程序 九、串口排查驱动原因及字符图片显示【转】
    tiny4412 裸机程序 八、重定位到DRAM及LCD实验【转】
    tiny4412 裸机程序 七、重定位代码到DRAM【转】
    tiny4412 裸机程序 六、重定位代码到IRAM+0x8000【转】
  • 原文地址:https://www.cnblogs.com/davidwang456/p/6018203.html
Copyright © 2011-2022 走看看