1 /* 2 * Copyright (c) 2016, 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 * @test 25 * @bug 8134918 26 * @modules java.base/jdk.internal.misc 27 * @run main/bootclasspath -XX:+IgnoreUnrecognizedVMOptions -XX:TypeProfileLevel=222 -XX:+UseTypeSpeculation -Xbatch 28 * -XX:CompileCommand=dontinline,UnsafeAccess::test* 29 * UnsafeAccess 30 */ 31 import jdk.internal.misc.Unsafe; 32 33 public class UnsafeAccess { 34 private static final Unsafe U = Unsafe.getUnsafe(); 35 36 static Class cls = Object.class; 37 static long off = U.ARRAY_OBJECT_BASE_OFFSET; 38 39 static Object testUnsafeAccess(Object o, boolean isObjArray) { 40 if (o != null && cls.isInstance(o)) { // speculates "o" type to int[] 41 return helperUnsafeAccess(o, isObjArray); 42 } 43 return null; 44 } 45 46 static Object helperUnsafeAccess(Object o, boolean isObjArray) { 47 if (isObjArray) { 48 U.putObject(o, off, new Object()); 49 } 50 return o; 51 } 52 53 static Object testUnsafeLoadStore(Object o, boolean isObjArray) { 54 if (o != null && cls.isInstance(o)) { // speculates "o" type to int[] 55 return helperUnsafeLoadStore(o, isObjArray); 56 } 57 return null; 58 } 59 60 static Object helperUnsafeLoadStore(Object o, boolean isObjArray) { 61 if (isObjArray) { 62 Object o1 = U.getObject(o, off); 63 U.compareAndSwapObject(o, off, o1, new Object()); 64 } 65 return o; 66 } 67 68 public static void main(String[] args) { 69 Object[] objArray = new Object[10]; 70 int[] intArray = new int[10]; 71 72 for (int i = 0; i < 20_000; i++) { 73 helperUnsafeAccess(objArray, true); 74 } 75 for (int i = 0; i < 20_000; i++) { 76 testUnsafeAccess(intArray, false); 77 } 78 79 for (int i = 0; i < 20_000; i++) { 80 helperUnsafeLoadStore(objArray, true); 81 } 82 for (int i = 0; i < 20_000; i++) { 83 testUnsafeLoadStore(intArray, false); 84 } 85 86 System.out.println("TEST PASSED"); 87 } 88 }