1 /*
  2  * Copyright (c) 2019, 2023, 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 java.lang.foreign.*;
 31 import java.lang.invoke.VarHandle;
 32 import java.nio.ByteBuffer;
 33 import java.util.ArrayList;
 34 import java.util.List;
 35 import java.util.Spliterator;
 36 import java.util.concurrent.CompletableFuture;
 37 import java.util.concurrent.CountDownLatch;
 38 import java.util.concurrent.atomic.AtomicInteger;
 39 
 40 import org.testng.annotations.*;
 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 (Arena arena = Arena.ofShared()) {
 52             MemorySegment s = arena.allocate(layout);;
 53             for (int i = 0 ; i < layout.elementCount() ; 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 (Arena arena = Arena.ofShared()) {
 97             MemorySegment s = arena.allocate(4, 1);;
 98             setInt(s, 42);
 99             assertEquals(getInt(s), 42);
100             List<Thread> threads = new ArrayList<>();
101             for (int i = 0 ; i < 1000 ; i++) {
102                 threads.add(new Thread(() -> {
103                     assertEquals(getInt(s), 42);
104                 }));
105             }
106             threads.forEach(Thread::start);
107             threads.forEach(t -> {
108                 try {
109                     t.join();
110                 } catch (Throwable e) {
111                     throw new IllegalStateException(e);
112                 }
113             });
114         }
115     }
116 
117     @Test
118     public void testOutsideConfinementThread() throws Throwable {
119         CountDownLatch a = new CountDownLatch(1);
120         CountDownLatch b = new CountDownLatch(1);
121         CompletableFuture<?> r;
122         try (Arena arena = Arena.ofConfined()) {
123             MemoryLayout layout = MemoryLayout.sequenceLayout(2, ValueLayout.JAVA_INT);
124             MemorySegment s1 = arena.allocate(layout);;
125             r = CompletableFuture.runAsync(() -> {
126                 try {
127                     ByteBuffer bb = s1.asByteBuffer();
128 
129                     MemorySegment s2 = MemorySegment.ofBuffer(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 (WrongThreadException 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, 0L);
154     }
155 
156     static void setInt(MemorySegment base, int value) {
157         intHandle.setVolatile(base, 0L, value);
158     }
159 }