1 /* 2 * Copyright (c) 2019, 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 /* 26 * @test 27 * @run testng TestSharedAccess 28 */ 29 30 import jdk.incubator.foreign.MemorySegment; 31 import jdk.incubator.foreign.MemoryLayouts; 32 import org.testng.annotations.*; 33 34 import java.lang.invoke.VarHandle; 35 import java.util.ArrayList; 36 import java.util.List; 37 38 import static org.testng.Assert.*; 39 40 public class TestSharedAccess { 41 42 static final VarHandle intHandle = MemoryLayouts.JAVA_INT.varHandle(int.class); 43 44 @Test 45 public void testShared() throws Throwable { 46 try (MemorySegment s = MemorySegment.allocateNative(4)) { 47 setInt(s, 42); 48 assertEquals(getInt(s), 42); 49 List<Thread> threads = new ArrayList<>(); 50 for (int i = 0 ; i < 1000 ; i++) { 51 threads.add(new Thread(() -> { 52 try (MemorySegment local = s.acquire()) { 53 assertEquals(getInt(local), 42); 54 } 55 })); 56 } 57 threads.forEach(Thread::start); 58 threads.forEach(t -> { 59 try { 60 t.join(); 61 } catch (Throwable e) { 62 throw new IllegalStateException(e); 63 } 64 }); 65 } 66 } 67 68 @Test(expectedExceptions=IllegalStateException.class) 69 public void testBadCloseWithPendingAcquire() { 70 try (MemorySegment segment = MemorySegment.allocateNative(8)) { 71 segment.acquire(); 72 } //should fail here! 73 } 74 75 static int getInt(MemorySegment handle) { 76 return (int)intHandle.getVolatile(handle.baseAddress()); 77 } 78 79 static void setInt(MemorySegment handle, int value) { 80 intHandle.setVolatile(handle.baseAddress(), value); 81 } 82 }