溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

hashmap是線程安全嗎

發(fā)布時間:2021-12-30 09:15:25 來源:億速云 閱讀:111 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“hashmap是線程安全嗎”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“hashmap是線程安全嗎”吧!

目前普遍都是使用jdk1.8 了。 其實要模擬jdk1.8的多線程不安全出來,其實很簡單的。

復(fù)制一份hashmap的代碼出來。接著 將 hashmap的容量固定為1 ,并且禁止擴容。

比如: 修改 resize代碼。 第一次可以擴展,容量是1。第二次就不可以了。

  final Node<K,V>[] resize() {

        if (FirstResize.get() !=0){
            System.out.println(">>>>不可以擴展>>>");
            return  table;
        }else{
            FirstResize.addAndGet(1);
        }

put 方法里面,進行控制線程的調(diào)度,就可以模擬了

 /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null){ // 多線程并發(fā),會發(fā)生 數(shù)據(jù)覆蓋
            if (Thread.currentThread().getName().equals("a")){
                System.out.println("線程A休眠,暫停執(zhí)行"); //模擬, 讓其覆蓋 其他線程 的值
                try {
                    Thread.sleep(5*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("i >>>>"+i);
            System.out.println("插入:"+key +": "+value);
            tab[i] = newNode(hash, key, value, null);
        }
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        //同理也會 發(fā)生并發(fā) put的時候被覆蓋的情況
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

測試代碼:

package com.interview.javabasic.myhashmap;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class TestThreadMap {
    
    
    private static HashMap<Integer,Integer> mh=new HashMap(1);

    public static void main(String[] args) {



        HashMapThread thread0 = new HashMapThread("a",mh);
        HashMapThread thread1 = new HashMapThread("b",mh);

        thread0.start();
        thread1.start();


        try {
            Thread.sleep(15*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 此時會發(fā)現(xiàn) map 里面  只有 2,2   。
        //  mh.put(3,3); 被覆蓋了
        System.out.println(mh);


    }

}


class HashMapThread extends Thread {
    HashMap<Integer,Integer> mh;

    private  String namet;
    public HashMapThread(String name, HashMap mh) {
        super(name);
        this.namet=name;
        this.mh=mh;
    }

    @Override
    public void run() {

        if (namet.equals("b")){
            try {
                Thread.sleep(2*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mh.put(3,3);
        }else{

            mh.put(2,2);
        }



    }
}

到此,相信大家對“hashmap是線程安全嗎”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI