1 /*
2  * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 package test.java.util.HashMap;
24 
25 /**
26  * @test
27  * @bug 7173432
28  * @summary If the key to be inserted into a HashMap is null and the table
29  * needs to be resized as part of the insertion then addEntry will try to
30  * recalculate the hash of a null key. This will fail with an NPE.
31  */
32 
33 import java.util.*;
34 
35 public class NullKeyAtResize {
main(String[] args)36     public static void main(String[] args) throws Exception {
37         List<Object> old_order = new ArrayList<>();
38         Map<Object,Object> m = new HashMap<>(16);
39         int number = 0;
40         while(number < 100000) {
41             m.put(null,null); // try to put in null. This may cause resize.
42             m.remove(null); // remove it.
43             Integer adding = (number += 100);
44             m.put(adding, null); // try to put in a number. This wont cause resize.
45             List<Object> new_order = new ArrayList<>();
46             new_order.addAll(m.keySet());
47             new_order.remove(adding);
48             if(!old_order.equals(new_order)) {
49                 // we resized and didn't crash.
50                 System.out.println("Encountered resize after " + (number / 100) + " iterations");
51                 break;
52             }
53             // remember this order for the next time around.
54             old_order.clear();
55             old_order.addAll(m.keySet());
56         }
57         if(number == 100000) {
58             throw new Error("Resize never occurred");
59         }
60     }
61 }
62