HashMap并发下产生的问题

产生的问题

在JDK1.8中并发下使用线程非安全的HashMap,会产生死循环的问题,put时数据丢失问题,容量size的不准确,重Hash问题。这也只是基本的一些问题,在多线程下HashMap会出现的问题个人觉得还不止这些。

原因描述

1、死循环问题描述

在1.8中,引入了红黑树优化数组链表,同时改成了尾插,按理来说是不会有环了,但是还是会出现死循环的问题,在链表转换成红黑数的时候无法跳出等多个地方都会出现这个问题。

2、put数据丢失描述

在下方代码注释处,线程已经拿到了头结点和hash桶,若此时cpu挂起,重新进入执行前,这个hash桶已经被其他线程更改过,那么在该线程重入后,他将持有一个过期的桶和头结点,并且覆盖之前其他线程的记录,造成了数据丢失。

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 线程已经拿到了头结点和hash桶
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            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) {
                        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;
    }
3、size不准确描述

size只是用了transient(不参与序列化)关键字修饰,在各个线程中的size不会及时同步,在多个线程操作的时候,size将会被覆盖。

transient Set<Map.Entry<K,V>> entrySet;

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
是的,这个接口有并发问题。在多线程环境下,多个线程可以同时访问 `login` 方法,从而可能导致数据竞争和线程安全问题。具体来说,如果两个线程同时访问 `login` 方法,并尝试更新 `users` 哈希表,可能会导致哈希表数据不一致或可能导致 `ConcurrentModificationException` 异常。 为了解决这些并发问题,您可以使用同步机制来确保 `login` 方法在同一时间只能由一个线程访问。例如,您可以使用 `synchronized` 关键字将 `login` 方法标记为同步方法,如下所示: ``` public synchronized boolean login(String username, String password) { // ... } ``` 这将确保在任何时候只有一个线程可以访问 `login` 方法。但是,这可能会对性能产生负面影响,并且可能导致线程阻塞。 另一种解决方案是使用线程安全的数据结构,例如 `ConcurrentHashMap`。这个哈希表是线程安全的,可以在多线程环境下安全地更新。您可以使用 `ConcurrentHashMap` 替换 `HashMap`,以确保在多线程环境下 `users` 哈希表的线程安全。例如: ``` import java.util.concurrent.ConcurrentHashMap; public class LoginController { private ConcurrentHashMap<String, String> users = new ConcurrentHashMap<String, String>(); public LoginController() { // 在此处添加用户数据,例如: users.put("user1", "password1"); users.put("user2", "password2"); users.put("user3", "password3"); } public boolean login(String username, String password) { // 如果用户名和密码匹配,则返回 true,否则返回 false if (users.containsKey(username) && users.get(username).equals(password)) { return true; } return false; } } ``` 使用 `ConcurrentHashMap` 可以确保在多线程环境下,`users` 哈希表的线程安全。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值