Home >Java >JavaBase >What is the difference between hashmap and concurrenthashmap

What is the difference between hashmap and concurrenthashmap

青灯夜游
青灯夜游Original
2021-02-02 11:14:1812651browse

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.

What is the difference between hashmap and concurrenthashmap

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

What is the difference between hashmap and concurrenthashmap

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.

What is the difference between hashmap and concurrenthashmap

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

What is the difference between hashmap and concurrenthashmap

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.

What is the difference between hashmap and concurrenthashmap

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

What is the difference between hashmap and concurrenthashmap

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn