Path: blob/master/test/jdk/java/util/HashMap/HashMapCloneLeak.java
41149 views
/*1* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 704212626* @summary Verify that we do not leak contents when we clone a HashMap27* @author [email protected]28* @run main/othervm HashMapCloneLeak29* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+EliminateAutoBox -XX:AutoBoxCacheMax=20000 HashMapCloneLeak30*/3132import java.util.HashMap;33import java.lang.ref.WeakReference;3435public class HashMapCloneLeak {3637static WeakReference<Object> wr = null;3839// helper method to keep testObject and map out of main method's scope40private static HashMap<Integer, Object> makeMap() {41HashMap<Integer, Object> map = new HashMap<Integer, Object>();42Object testObject = new Object();43wr = new WeakReference<Object>(testObject);44map.put(42, testObject);45return map;46}4748public static void main(String[] args) throws Exception {49HashMap<Integer, Object> hm = makeMap();50hm = (HashMap<Integer, Object>)hm.clone();51hm.clear();52// There should no longer be a strong reference to testObject53// the WeakReference should be nulled out by GC. If not,54// we will hang here until timed out by the test harness.55Object[] chain = null;56while (wr.get() != null) {57try {58Object[] allocate = new Object[1000000];59allocate[0] = chain;60chain = allocate;61} catch (OutOfMemoryError oome) {62chain = null;63}64System.gc();65Thread.sleep(100);66}67}6869}707172