Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8046085

HashMap.put with null key may throw NullPointerException

XMLWordPrintable

    • b19
    • generic
    • generic
    • Verified

        FULL PRODUCT VERSION :
        java version "1.8.0_05"
        Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
        Java HotSpot(TM) Client VM (build 25.5-b02, mixed mode, sharing)

        ADDITIONAL OS VERSION INFORMATION :
        Microsoft Windows [Version 6.1.7601]

        A DESCRIPTION OF THE PROBLEM :
        Changes to improve HashMap performance in Java 8 can cause HashMap.put() with a null key to throw a NullPointerException. This problem did not occur in Java 7.

        Caused by: java.lang.NullPointerException
            at java.util.HashMap$TreeNode.putTreeVal(HashMap.java:1970)
            at java.util.HashMap.putVal(HashMap.java:637)
            at java.util.HashMap.put(HashMap.java:611)

        It looks like the line of code in question is
        else if ((pk = p.key) == k || (pk != null && k.equals(pk)))

        Probably k.equals(pk) is source of the NullPointerException where k is null.
        Possibly fix is change it to pk.equals(k).


        REGRESSION. Last worked in version 7u17

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        Problem occurs on continuous build machine during unit test. Unit test is parsing XML and custom ContentHandler is saving data to a HashMap.

        /* HashMap for saving parsed data */
            private static final ThreadLocal contextMap = new ThreadLocal() {
                protected Object initialValue() {
                    return new HashMap();
                }
            };

        /* Insertion of data into HashMap */
            Map map = (Map) contextMap.get();
            map.put(key, value);

        Problem has not occurred on development machine with limited testing, but consistently fails on build machine.


        ERROR MESSAGES/STACK TRACES THAT OCCUR :
        Caused by: java.lang.NullPointerException
            at java.util.HashMap$TreeNode.putTreeVal(HashMap.java:1970)
            at java.util.HashMap.putVal(HashMap.java:637)
            at java.util.HashMap.put(HashMap.java:611)


        REPRODUCIBILITY :
        This bug can be reproduced often.

        CUSTOMER SUBMITTED WORKAROUND :
        Check if key or value is not null, then insert into map.

              mduigou Mike Duigou
              webbuggrp Webbug Group
              Votes:
              1 Vote for this issue
              Watchers:
              8 Start watching this issue

                Created:
                Updated:
                Resolved: