其他分享
首页 > 其他分享> > JDK8 HashMap也会死循环

JDK8 HashMap也会死循环

作者:互联网

前言

问题复现

public class Test {

    private static Map<String, String> map = new HashMap<>();

    @SneakyThrows
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(2);
        // 线程1 => t1
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100_0000; i++) {
                    map.put("thread1_key" + i, "thread1_value" + i);
                    if (i%10_0000==0) {
                        System.out.println("thread1 put 10W");
                    }
                }
                System.out.println("thread1 end");
                latch.countDown();
            }
        },"thread one").start();
        // 线程2 => t2
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100_0000; i++) {
                    map.put("thread2_key" + i, "thread2_value" + i);
                    if (i%10_0000==0) {
                        System.out.println("thread2 put 10W");
                    }
                }
                System.out.println("thread2 end");
                latch.countDown();
            }
        },"thread tow").start();
        latch.await();

        //使用JDK1.8
        //没有并发问题应该为:200_0000
        // 实际可能会小于200_0000
        // 实际可能会抛出异常:红黑树的异常,只复现了一次,没有保留结果
        // 实际可能会死循环,用尾插法解决了链表的死循环,但是红黑树还有可能死循环
        //   下面是线程信息
        //   "thread tow" #15 prio=5 os_prio=0 cpu=37656.25ms elapsed=38.05s tid=0x0000018a938c8800 nid=0x3478 runnable  [0x000000066e8fd000]
        //   java.lang.Thread.State: RUNNABLE
        //	   at java.util.HashMap$TreeNode.balanceInsertion(java.base@11.0.5/HashMap.java:2286)
        //	   at java.util.HashMap$TreeNode.treeify(java.base@11.0.5/HashMap.java:1992)
        //	   at java.util.HashMap$TreeNode.split(java.base@11.0.5/HashMap.java:2218)
        //	   at java.util.HashMap.resize(java.base@11.0.5/HashMap.java:709)
        //	   at java.util.HashMap.putVal(java.base@11.0.5/HashMap.java:658)
        //	   at java.util.HashMap.put(java.base@11.0.5/HashMap.java:607)
        //	   at com.spacedo.collocation.Test$2.run(Test.java:35)
        //	   at java.lang.Thread.run(java.base@11.0.5/Thread.java:834)
        //
        //   Locked ownable synchronizers:
        //	- None
        System.out.println(map.size());
    }
}

标签:util,java,HashMap,11.0,链表,JDK8,base,死循环
来源: https://blog.csdn.net/aajjw/article/details/120581508