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