1/*
2 * Copyright (c) 2013, 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
24/**
25 * @test
26 * @bug 7042126
27 * @summary Verify that we do not leak contents when we clone a HashMap
28 * @author david.buck@oracle.com
29 * @run main/othervm HashMapCloneLeak
30 * @run main/othervm -XX:+AggressiveOpts HashMapCloneLeak
31 */
32
33import java.util.HashMap;
34import java.lang.ref.WeakReference;
35
36public class HashMapCloneLeak {
37
38    static WeakReference<Object> wr = null;
39
40    // helper method to keep testObject and map out of main method's scope
41    private static HashMap<Integer, Object> makeMap() {
42        HashMap<Integer, Object> map = new HashMap<Integer, Object>();
43        Object testObject = new Object();
44        wr = new WeakReference<Object>(testObject);
45        map.put(42, testObject);
46        return map;
47    }
48
49    public static void main(String[] args) throws Exception {
50        HashMap<Integer, Object> hm = makeMap();
51        hm = (HashMap<Integer, Object>)hm.clone();
52        hm.clear();
53        // There should no longer be a strong reference to testObject
54        // the WeakReference should be nulled out by GC. If not,
55        // we will hang here until timed out by the test harness.
56        Object[] chain = null;
57        while (wr.get() != null) {
58            try {
59                Object[] allocate = new Object[1000000];
60                allocate[0] = chain;
61                chain = allocate;
62            } catch (OutOfMemoryError oome) {
63                chain = null;
64            }
65            System.gc();
66            Thread.sleep(100);
67        }
68    }
69
70}
71