Difference: HashMap is thread-unsafe. When multi-threaded operations occur, security risks may occur; while ConcurrentHashMap is thread-safe. HashMap does not support concurrent operations and has no synchronization method; ConcurrentHashMap supports concurrent operations.
The operating environment of this tutorial: windows7 system, java10 version, DELL G3 computer.
The difference between hashmap and concurrenthashmap
HashMap is thread-unsafe. When multi-threaded operations occur, security risks will occur; while ConcurrentHashMap Is thread safe.
HashMap does not support concurrent operations and has no synchronization method. ConcurrentHashMap supports concurrent operations by inheriting ReentrantLock (JDK1.7 reentrant lock)/CAS and synchronized (JDK1.8 built-in lock) When locking (segment locking), each operation that needs to be locked locks a segment. In this way, as long as each segment is thread-safe, global thread safety is achieved.
ConcurrentHashMap uses lock segmentation technology to segment the entire Hash bucket, that is, this large array is divided into several small segments, and each small segment There are locks on the segment segments, so when inserting elements, you need to first find which segment segment should be inserted, and then insert on this segment, and you also need to obtain the segment lock here.
ConcurrentHashMap makes the lock granularity more refined and the concurrency performance better.
(Recommended tutorial: java introductory tutorial)
HashMap
HashMap is thread-unsafe. The put method does not handle locks. When multiple threads are released, there will be thread safety issues. Here is a simple example to demonstrate. Three threads are created and started. In the run method, 100 values are stored in the map through a for loop. , and then output the size of the map. Normally, the size of the map should be 100, but 176 is output here.
class Demo implements Runnable{ static Map<String,String> map = new HashMap<>(); @Override public void run() { for (int i = 0; i < 100; i ++) { map.put(i + "","value"); } } public static void main(String[] args) { new Thread(new Demo()).start(); new Thread(new Demo()).start(); new Thread(new Demo()).start(); // 获取当前线程 Thread currentThread = Thread.currentThread(); // 当前线程睡眠2秒,让上面的三个线程先执行 try { currentThread.sleep(2000); } catch (Exception e) { e.getMessage(); } // 上面的线程执行完毕后输出map的大小 System.out.println(map.size()); } }
HashTable
HashTable uses a lock, and the lock is added directly to the put method. The thread is definitely safe. , here we are testing thread safety while taking a look at the execution time. Here we put10000 data for testing. From the results, we can see that the size of the map is indeed 10000, and the time took about 16ms.
class Demo implements Runnable{ static Map<String,String> map = new Hashtable<>(); @Override public void run() { long startTime = System.currentTimeMillis(); //获取开始时间 for (int i = 0; i < 10000; i ++) { map.put(i + "","value"); } long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println((endTime - startTime) + "ms"); } public static void main(String[] args) { new Thread(new Demo()).start(); new Thread(new Demo()).start(); new Thread(new Demo()).start(); // 获取当前线程 Thread currentThread = Thread.currentThread(); // 当前线程睡眠2秒,让上面的三个线程先执行 try { currentThread.sleep(2000); } catch (Exception e) { e.getMessage(); } // 上面的线程执行完毕后输出map的大小 System.out.println(map.size()); } }
ConcurrentHashMap
ConcurrentHashMap uses segmentation lock, which block is unsafe Just lock which part, if you can’t leave it unlocked, or if you can’t lock it all, then I’ll lock it! See whether this block lock is faster or slower than the method lock.
class Demo implements Runnable{ static Map<String,String> map = new ConcurrentHashMap<>(); @Override public void run() { long startTime = System.currentTimeMillis(); //获取开始时间 for (int i = 0; i < 10000; i ++) { map.put(i + "","value"); } long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println((endTime - startTime) + "ms"); } public static void main(String[] args) { new Thread(new Demo()).start(); new Thread(new Demo()).start(); new Thread(new Demo()).start(); // 获取当前线程 Thread currentThread = Thread.currentThread(); // 当前线程睡眠2秒,让上面的三个线程先执行 try { currentThread.sleep(2000); } catch (Exception e) { e.getMessage(); } // 上面的线程执行完毕后输出map的大小 System.out.println(map.size()); } }
It can be seen from the results that it has improved from the previous 20ms and 22ms to the current 17ms and 18ms
For more computer programming related knowledge, please visit: programming video! !
The above is the detailed content of What is the difference between hashmap and concurrenthashmap. For more information, please follow other related articles on the PHP Chinese website!

hashmap的扩容机制是:重新计算容量,用一个新的数组替换原来的数组。重新计算原数组的所有数据并插入一个新数组,然后指向新数组;如果数组在容量扩展前已达到最大值,则直接将阈值设置为最大整数返回。

如何使用HashMap类的put()方法将键值对插入到HashMap中HashMap是Java集合框架中的一个非常重要的类,它提供了一种存储键值对的方式。在实际开发中,我们经常需要向HashMap中插入键值对,通过使用HashMap类的put()方法可以很轻松地实现这一目标。HashMap的put()方法的签名如下:Vput(Kkey,Vvalue)

Java文档解读:HashMap类的containsKey()方法用法详解,需要具体代码示例引言:HashMap是Java中常用的一种数据结构,它提供了高效的存储和查找功能。其中的containsKey()方法用于判断HashMap中是否包含指定的键。本文将详细解读HashMap类的containsKey()方法的使用方式,并提供具体的代码示例。一、cont

1、说明Map基本上可以使用HashMap,但是HashMap有一个问题,那就是迭代HashMap的顺序不是HashMap放置的顺序,就是无序。HashMap的这个缺点往往会带来麻烦,因为有些场景我们期待一个有序的Map,这就是LinkedHashMap。2、区别实例publicstaticvoidmain(String[]args){Mapmap=newLinkedHashMap();map.put("apple","苹果");map.put("

一、单例模式是什么?单例模式是一种对象创建模式,它用于产生一个对象的具体实例,它可以确保系统中一个类只产生一个实例。Java里面实现的单例是一个虚拟机的范围,因为装载类的功能是虚拟机的,所以一个虚拟机在通过自己的ClassLoad装载实现单例类的时候就会创建一个类的实例。在Java语言中,这样的行为能带来两大好处:1.对于频繁使用的对象,可以省略创建对象所花费的时间,这对于那些重量级对象而言,是非常可观的一笔系统开销;2.由于new操作的次数减少,因而对系统内存的使用频率也会降低,这将减轻GC压

JavaMap是Java标准库中常用的数据结构,它以键值对的形式存储数据。Map的性能对于应用程序的运行效率至关重要,如果Map的性能不佳,可能会导致应用程序运行缓慢,甚至崩溃。1.选择合适的Map实现Java提供了多种Map实现,包括HashMap、TreeMap和LinkedHashMap。每种Map实现都有其各自的优缺点,在选择Map实现时,需要根据应用程序的具体需求来选择合适的实现。HashMap:HashMap是最常用的Map实现,它使用哈希表来存储数据,具有较快的插入、删除和查找速度

Java使用HashMap类的putAll()函数将一个Map添加到另一个Map中Map是Java中常用的数据结构,用来表示键值对的集合。在Java的集合框架中,HashMap是一个常用的实现类。它提供了putAll()函数,用于将一个Map添加到另一个Map中,方便实现数据的合并和拷贝。本文将介绍putAll()函数的使用方法,并提供相应的代码示例。首先,

javaHashMap插入重复Key值要在HashMap中插入重复的值,首先需要弄清楚HashMap里面是怎么存放元素的。put方法Map里面存放的每一个元素都是key-value这样的键值对,而且都是通过put方法进行添加的,而且相同的key在Map中只会有一个与之关联的value存在。put方法在Map中的定义如下。Vput(Kkey,Vvalue);put()方法实现:首先hash(key)得到key的hashcode(),hashmap根据获得的hashcode找到要插入的位置所在的链,


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor
