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/othervm --enable-native-access=ALL-UNNAMED TestSharedAccess
 28  */
 29 
 30 import jdk.incubator.foreign.*;
 31 import org.testng.annotations.*;
 32 
 33 import java.lang.invoke.VarHandle;
 34 import java.nio.ByteBuffer;
 35 import java.util.ArrayList;
 36 import java.util.List;
 37 import java.util.Spliterator;
 38 import java.util.concurrent.CompletableFuture;
 39 import java.util.concurrent.CountDownLatch;
 40 import java.util.concurrent.atomic.AtomicInteger;
 41 
 42 import static org.testng.Assert.*;
 43 
 44 public class TestSharedAccess {
 45 
 46     static final VarHandle intHandle = ValueLayout.JAVA_INT.varHandle();
 47 
 48     @Test
 49     public void testShared() throws Throwable {
 50         SequenceLayout layout = MemoryLayout.sequenceLayout(1024, ValueLayout.JAVA_INT);
 51         try (ResourceScope scope = ResourceScope.newSharedScope()) {
 52             MemorySegment s = MemorySegment.allocateNative(layout, scope);
 53             for (int i = 0 ; i < layout.elementCount().getAsLong() ; i++) {
 54                 setInt(s.asSlice(i * 4), 42);
 55             }
 56             List<Thread> threads = new ArrayList<>();
 57             List<Spliterator<MemorySegment>> spliterators = new ArrayList<>();
 58             spliterators.add(s.spliterator(layout.elementLayout()));
 59             while (true) {
 60                 boolean progress = false;
 61                 List<Spliterator<MemorySegment>> newSpliterators = new ArrayList<>();
 62                 for (Spliterator<MemorySegment> spliterator : spliterators) {
 63                     Spliterator<MemorySegment> sub = spliterator.trySplit();
 64                     if (sub != null) {
 65                         progress = true;
 66                         newSpliterators.add(sub);
 67                     }
 68                 }
 69                 spliterators.addAll(newSpliterators);
 70                 if (!progress) break;
 71             }
 72 
 73             AtomicInteger accessCount = new AtomicInteger();
 74             for (Spliterator<MemorySegment> spliterator : spliterators) {
 75                 threads.add(new Thread(() -> {
 76                     spliterator.tryAdvance(local -> {
 77                         assertEquals(getInt(local), 42);
 78                         accessCount.incrementAndGet();
 79                     });
 80                 }));
 81             }
 82             threads.forEach(Thread::start);
 83             threads.forEach(t -> {
 84                 try {
 85                     t.join();
 86                 } catch (Throwable e) {
 87                     throw new IllegalStateException(e);
 88                 }
 89             });
 90             assertEquals(accessCount.get(), 1024);
 91         }
 92     }
 93 
 94     @Test
 95     public void testSharedUnsafe() throws Throwable {
 96         try (ResourceScope scope = ResourceScope.newSharedScope()) {
 97             MemorySegment s = MemorySegment.allocateNative(4, 1, scope);
 98             setInt(s, 42);
 99             assertEquals(getInt(s), 42);
100             List<Thread> threads = new ArrayList<>();
101             MemorySegment sharedSegment = MemorySegment.ofAddressNative(s.address(), s.byteSize(), scope);
102             for (int i = 0 ; i < 1000 ; i++) {
103                 threads.add(new Thread(() -> {
104                     assertEquals(getInt(sharedSegment), 42);
105                 }));
106             }
107             threads.forEach(Thread::start);
108             threads.forEach(t -> {
109                 try {
110                     t.join();
111                 } catch (Throwable e) {
112                     throw new IllegalStateException(e);
113                 }
114             });
115         }
116     }
117 
118     @Test
119     public void testOutsideConfinementThread() throws Throwable {
120         CountDownLatch a = new CountDownLatch(1);
121         CountDownLatch b = new CountDownLatch(1);
122         CompletableFuture<?> r;
123         try (ResourceScope scope = ResourceScope.newConfinedScope()) {
124             MemorySegment s1 = MemorySegment.allocateNative(MemoryLayout.sequenceLayout(2, ValueLayout.JAVA_INT), scope);
125             r = CompletableFuture.runAsync(() -> {
126                 try {
127                     ByteBuffer bb = s1.asByteBuffer();
128 
129                     MemorySegment s2 = MemorySegment.ofByteBuffer(bb);
130                     a.countDown();
131 
132                     try {
133                         b.await();
134                     } catch (InterruptedException e) {
135                     }
136 
137                     setInt(s2.asSlice(4), -42);
138                     fail();
139                 } catch (IllegalStateException ex) {
140                     assertTrue(ex.getMessage().contains("owning thread"));
141                 }
142             });
143 
144             a.await();
145             setInt(s1.asSlice(4), 42);
146         }
147 
148         b.countDown();
149         r.get();
150     }
151 
152     static int getInt(MemorySegment base) {
153         return (int)intHandle.getVolatile(base);
154     }
155 
156     static void setInt(MemorySegment base, int value) {
157         intHandle.setVolatile(base, value);
158     }
159 }