美文网首页程序员
Hashmap和List小结

Hashmap和List小结

作者: 长弘羲雨 | 来源:发表于2020-05-19 16:03 被阅读0次

    tags: [JAVA]
    categories: 技术

    List 中获取相同元素出现次数,得到元素和次数对应的 map

    //获取最外层循环(每个信息类的总数量)
    HashMap <String,Integer>mp = new HashMap<String,Integer>();
    int tableNameCount = 1;
    List tableNameAndCountList = new ArrayList<>();
    for(int k = 0; k < tables.size(); k++ ){
        if(mp.containsKey(tables.get(k).get("tablename"))){
            mp.put(tables.get(k).get("tablename").toString(), mp.get(tables.get(k).get("tablename")).intValue()+tableNameCount);
            }
        else{
            mp.put(tables.get(k).get("tablename").toString(), tableNameCount);
            }
    }
    

    关于 HashMap 安全性

    因为 HashTable 存在速度慢等问题,所以线程安全的 HashMap 很有必要,因为是 Hashtable 是使用 synchronized 的,所有线程竞争同一把锁;而 ConcurrentHashMap 不仅线程安全而且效率高,因为它包含一个 segment 数组,将数据分段存储,给每一段数据配一把锁,也就是所谓的锁分段技术。

    //Hashtable
    Map<String, String> hashtable = new Hashtable<>();
    //synchronizedMap
    Map<String, String> synchronizedHashMap = Collections.synchronizedMap(new HashMap<String, String>());
    //ConcurrentHashMap
    Map<String, String> concurrentHashMap = new ConcurrentHashMap<>();
    
    • 什么时候使用 ConcurrentHashMap

    CHM 适用于读者数量超过写者时,当写者数量大于等于读者时,CHM 的性能是低于 Hashtable 和 synchronized Map 的。这是因为当锁住了整个 Map 时,读操作要等待对同一部分执行写操作的线程结束。CHM 适用于做 cache,在程序启动时初始化,之后可以被多个请求线程访问。正如 Javadoc 说明的那样,CHM 是 HashTable 一个很好的替代,但要记住,CHM 的比 HashTable 的同步性稍弱。

    • 性能对比

    这是要靠数据说话的时代,所以不能只靠嘴说 CHM 快,它就快了。写个测试用例,实际的比较一下这三种方式的效率(源码来源),下面的代码分别通过三种方式创建 Map 对象,使用 ExecutorService 来并发运行 5 个线程,每个线程添加/获取 500K 个元素。

    public class CrunchifyConcurrentHashMapVsSynchronizedMap {
      public final static int THREAD_POOL_SIZE = 5;
      public static Map<String, Integer> crunchifyHashTableObject = null;
      public static Map<String, Integer> crunchifySynchronizedMapObject = null;
      public static Map<String, Integer> crunchifyConcurrentHashMapObject = null;
      public static void main(String[] args) throws InterruptedException {
      // Test with Hashtable Object
      crunchifyHashTableObject = new Hashtable<>();
      crunchifyPerformTest(crunchifyHashTableObject);
    
      // Test with synchronizedMap Object
      crunchifySynchronizedMapObject = Collections.synchronizedMap(new HashMap<String, Integer>());
      crunchifyPerformTest(crunchifySynchronizedMapObject);
    
      // Test with ConcurrentHashMap Object
      crunchifyConcurrentHashMapObject = new ConcurrentHashMap<>();
      crunchifyPerformTest(crunchifyConcurrentHashMapObject);
      }
      public static void crunchifyPerformTest(final Map<String, Integer> crunchifyThreads) throws InterruptedException {
    
      System.out.println("Test started for: " + crunchifyThreads.getClass());
      long averageTime = 0;
      for (int i = 0; i < 5; i++) {
    
          long startTime = System.nanoTime();
          ExecutorService crunchifyExServer = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    
          for (int j = 0; j < THREAD_POOL_SIZE; j++) {
              crunchifyExServer.execute(new Runnable() {
                  @SuppressWarnings("unused")
                  @Override
                  public void run() {
    
                      for (int i = 0; i < 500000; i++) {
                          Integer crunchifyRandomNumber = (int) Math.ceil(Math.random() * 550000);
    
                          // Retrieve value. We are not using it anywhere
                          Integer crunchifyValue = crunchifyThreads.get(String.valueOf(crunchifyRandomNumber));
    
                          // Put value
                          crunchifyThreads.put(String.valueOf(crunchifyRandomNumber), crunchifyRandomNumber);
                      }
                  }
              });
          }
    
          // Make sure executor stops
          crunchifyExServer.shutdown();
    
          // Blocks until all tasks have completed execution after a shutdown request
          crunchifyExServer.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    
          long entTime = System.nanoTime();
          long totalTime = (entTime - startTime) / 1000000L;
          averageTime += totalTime;
          System.out.println("2500K entried added/retrieved in " + totalTime + " ms");
      }
        System.out.println("For " + crunchifyThreads.getClass() + " the average time is " + averageTime / 5 + " ms\n");
        }
      }
    
    • 测试结果
    Test started for: class java.util.Hashtable
      2500K entried added/retrieved in 2018 ms
      2500K entried added/retrieved in 1746 ms
      2500K entried added/retrieved in 1806 ms
      2500K entried added/retrieved in 1801 ms
      2500K entried added/retrieved in 1804 ms
      For class java.util.Hashtable the average time is 1835 ms
    
      Test started for: class java.util.Collections$SynchronizedMap
      2500K entried added/retrieved in 3041 ms
      2500K entried added/retrieved in 1690 ms
      2500K entried added/retrieved in 1740 ms
      2500K entried added/retrieved in 1649 ms
      2500K entried added/retrieved in 1696 ms
      For class java.util.Collections$SynchronizedMap the average time is 1963 ms
    
      Test started for: class java.util.concurrent.ConcurrentHashMap
      2500K entried added/retrieved in 738 ms
      2500K entried added/retrieved in 696 ms
      2500K entried added/retrieved in 548 ms
      2500K entried added/retrieved in 1447 ms
      2500K entried added/retrieved in 531 ms
      For class java.util.concurrent.ConcurrentHashMap the average time is 792 ms
    

    相关文章

      网友评论

        本文标题:Hashmap和List小结

        本文链接:https://www.haomeiwen.com/subject/ezpbohtx.html