1 /*
  2  * Copyright (c) 2020, 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  * @test
 26  * @summary Test virtual threads using a custom scheduler
 27  * @requires vm.continuations
 28  * @modules java.base/java.lang:+open
 29  * @run junit CustomScheduler
 30  */
 31 
 32 import java.lang.reflect.Field;
 33 import java.time.Duration;
 34 import java.util.ArrayList;
 35 import java.util.List;
 36 import java.util.concurrent.*;
 37 import java.util.concurrent.atomic.AtomicBoolean;
 38 import java.util.concurrent.atomic.AtomicReference;
 39 import java.util.concurrent.locks.LockSupport;
 40 
 41 import org.junit.jupiter.api.Test;
 42 import org.junit.jupiter.api.BeforeAll;
 43 import org.junit.jupiter.api.AfterAll;
 44 import static org.junit.jupiter.api.Assertions.*;
 45 import static org.junit.jupiter.api.Assumptions.*;
 46 
 47 class CustomScheduler {
 48     private static final Executor DEFAULT_SCHEDULER = defaultScheduler();
 49     private static ExecutorService scheduler1;
 50     private static ExecutorService scheduler2;
 51 
 52     @BeforeAll
 53     static void setup() {
 54         scheduler1 = Executors.newFixedThreadPool(1);
 55         scheduler2 = Executors.newFixedThreadPool(1);
 56     }
 57 
 58     @AfterAll
 59     static void shutdown() {
 60         scheduler1.shutdown();
 61         scheduler2.shutdown();
 62     }
 63 
 64     /**
 65      * Test platform thread creating a virtual thread that uses a custom scheduler.
 66      */
 67     @Test
 68     void testCustomScheduler1() throws Exception {
 69         AtomicReference<Executor> ref = new AtomicReference<>();
 70         ThreadBuilders.virtualThreadBuilder(scheduler1).start(() -> {
 71             ref.set(scheduler(Thread.currentThread()));
 72         }).join();
 73         assertTrue(ref.get() == scheduler1);
 74     }
 75 
 76     /**
 77      * Test virtual thread creating a virtual thread that uses a custom scheduler.
 78      */
 79     @Test
 80     void testCustomScheduler2() throws Exception {
 81         AtomicReference<Executor> ref = new AtomicReference<>();
 82         Thread.ofVirtual().start(() -> {
 83             try {
 84                 ThreadBuilders.virtualThreadBuilder(scheduler1).start(() -> {
 85                     ref.set(scheduler(Thread.currentThread()));
 86                 }).join();
 87             } catch (Exception e) {
 88                 e.printStackTrace();
 89             }
 90         }).join();
 91         assertTrue(ref.get() == scheduler1);
 92     }
 93 
 94     /**
 95      * Test virtual thread using custom scheduler creating a virtual thread.
 96      * The scheduler should be inherited.
 97      */
 98     @Test
 99     void testCustomScheduler3() throws Exception {
100         AtomicReference<Executor> ref = new AtomicReference<>();
101         ThreadBuilders.virtualThreadBuilder(scheduler1).start(() -> {
102             try {
103                 Thread.ofVirtual().start(() -> {
104                     ref.set(scheduler(Thread.currentThread()));
105                 }).join();
106             } catch (Exception e) {
107                 e.printStackTrace();
108             }
109         }).join();
110         assertTrue(ref.get() == scheduler1);
111     }
112 
113     /**
114      * Test virtual thread using custom scheduler creating a virtual thread
115      * that uses a different custom scheduler.
116      */
117     @Test
118     void testCustomScheduler4() throws Exception {
119         AtomicReference<Executor> ref = new AtomicReference<>();
120         ThreadBuilders.virtualThreadBuilder(scheduler1).start(() -> {
121             try {
122                 ThreadBuilders.virtualThreadBuilder(scheduler2).start(() -> {
123                     ref.set(scheduler(Thread.currentThread()));
124                 }).join();
125             } catch (Exception e) {
126                 e.printStackTrace();
127             }
128         }).join();
129         assertTrue(ref.get() == scheduler2);
130     }
131 
132     /**
133      * Test running task on a virtual thread, should thrown WrongThreadException.
134      */
135     @Test
136     void testBadCarrier() {
137         Executor scheduler = (task) -> {
138             var exc = new AtomicReference<Throwable>();
139             try {
140                 Thread.ofVirtual().start(() -> {
141                     try {
142                         task.run();
143                         fail();
144                     } catch (Throwable e) {
145                         exc.set(e);
146                     }
147                 }).join();
148             } catch (InterruptedException e) {
149                 fail();
150             }
151             assertTrue(exc.get() instanceof WrongThreadException);
152         };
153 
154         ThreadBuilders.virtualThreadBuilder(scheduler).start(LockSupport::park);
155     }
156 
157     /**
158      * Test parking with the virtual thread interrupt set, should not leak to the
159      * carrier thread when the task completes.
160      */
161     @Test
162     void testParkWithInterruptSet() {
163         Thread carrier = Thread.currentThread();
164         assumeFalse(carrier.isVirtual(), "Main thread is a virtual thread");
165         try {
166             var builder = ThreadBuilders.virtualThreadBuilder(Runnable::run);
167             Thread vthread = builder.start(() -> {
168                 Thread.currentThread().interrupt();
169                 Thread.yield();
170             });
171             assertTrue(vthread.isInterrupted());
172             assertFalse(carrier.isInterrupted());
173         } finally {
174             Thread.interrupted();
175         }
176     }
177 
178     /**
179      * Test terminating with the virtual thread interrupt set, should not leak to
180      * the carrier thread when the task completes.
181      */
182     @Test
183     void testTerminateWithInterruptSet() {
184         Thread carrier = Thread.currentThread();
185         assumeFalse(carrier.isVirtual(), "Main thread is a virtual thread");
186         try {
187             var builder = ThreadBuilders.virtualThreadBuilder(Runnable::run);
188             Thread vthread = builder.start(() -> {
189                 Thread.currentThread().interrupt();
190             });
191             assertTrue(vthread.isInterrupted());
192             assertFalse(carrier.isInterrupted());
193         } finally {
194             Thread.interrupted();
195         }
196     }
197 
198     /**
199      * Test running task with the carrier interrupt status set.
200      */
201     @Test
202     void testRunWithInterruptSet() throws Exception {
203         assumeFalse(Thread.currentThread().isVirtual(), "Main thread is a virtual thread");
204         Executor scheduler = (task) -> {
205             Thread.currentThread().interrupt();
206             task.run();
207         };
208         try {
209             AtomicBoolean interrupted = new AtomicBoolean();
210             Thread vthread = ThreadBuilders.virtualThreadBuilder(scheduler).start(() -> {
211                 interrupted.set(Thread.currentThread().isInterrupted());
212             });
213             assertFalse(vthread.isInterrupted());
214         } finally {
215             Thread.interrupted();
216         }
217     }
218 
219     /**
220      * Returns the default scheduler.
221      */
222     private static Executor defaultScheduler() {
223         try {
224             Field defaultScheduler = Class.forName("java.lang.VirtualThread")
225                     .getDeclaredField("DEFAULT_SCHEDULER");
226             defaultScheduler.setAccessible(true);
227             return (Executor) defaultScheduler.get(null);
228         } catch (Exception e) {
229             throw new RuntimeException(e);
230         }
231     }
232 
233     /**
234      * Returns the scheduler for the given virtual thread.
235      */
236     private static Executor scheduler(Thread thread) {
237         if (!thread.isVirtual())
238             throw new IllegalArgumentException("Not a virtual thread");
239         try {
240             Field scheduler = Class.forName("java.lang.VirtualThread")
241                     .getDeclaredField("scheduler");
242             scheduler.setAccessible(true);
243             return (Executor) scheduler.get(thread);
244         } catch (Exception e) {
245             throw new RuntimeException(e);
246         }
247     }
248 }