1 /*
  2  * Copyright (c) 2020, 2024, 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 core reflection
 27  * @modules java.base/java.lang:+open
 28  * @library /test/lib
 29  * @run junit Reflection
 30  */
 31 
 32 import java.lang.reflect.Constructor;
 33 import java.lang.reflect.InvocationTargetException;
 34 import java.lang.reflect.Method;
 35 import java.util.concurrent.CountDownLatch;
 36 import java.util.concurrent.ExecutorService;
 37 import java.util.concurrent.Executors;
 38 import java.util.concurrent.ThreadFactory;
 39 import java.util.concurrent.locks.LockSupport;
 40 
 41 import jdk.test.lib.thread.VThreadScheduler;
 42 import jdk.test.lib.thread.VThreadRunner;
 43 import org.junit.jupiter.api.Test;
 44 import static org.junit.jupiter.api.Assertions.*;
 45 import static org.junit.jupiter.api.Assumptions.*;
 46 
 47 class Reflection {
 48 
 49     /**
 50      * Test invoking static method.
 51      */
 52     @Test
 53     void testInvokeStatic1() throws Exception {
 54         VThreadRunner.run(() -> {
 55             int result = (int) divideMethod().invoke(null, 20, 2);
 56             assertTrue(result == 10);
 57         });
 58     }
 59 
 60     /**
 61      * Test that InvocationTargetException is thrown when a static method throws
 62      * exception.
 63      */
 64     @Test
 65     void testInvokeStatic2() throws Exception {
 66         VThreadRunner.run(() -> {
 67             try {
 68                 divideMethod().invoke(null, 20, 0);
 69                 fail();
 70             } catch (InvocationTargetException e) {
 71                 assertTrue(e.getCause() instanceof ArithmeticException);
 72             }
 73         });
 74     }
 75 
 76     /**
 77      * Test that IllegalArgumentException is thrown when trying to invoke a static
 78      * method with bad parameters.
 79      */
 80     @Test
 81     void testInvokeStatic3() throws Exception {
 82         VThreadRunner.run(() -> {
 83             assertThrows(IllegalArgumentException.class,
 84                     () -> divideMethod().invoke(null));
 85             assertThrows(IllegalArgumentException.class,
 86                     () -> divideMethod().invoke(null, 1));
 87             assertThrows(IllegalArgumentException.class,
 88                     () -> divideMethod().invoke(null, 1, 2, 3));
 89             assertThrows(IllegalArgumentException.class,
 90                     () -> divideMethod().invoke(new Object()));
 91             assertThrows(IllegalArgumentException.class,
 92                     () -> divideMethod().invoke(new Object(), 1));
 93             assertThrows(IllegalArgumentException.class,
 94                     () -> divideMethod().invoke(new Object(), 1, 2, 3));
 95         });
 96     }
 97 
 98     /**
 99      * Test that ExceptionInInitializerError is thrown when invoking a static
100      * method triggers its class to be initialized and it fails with exception.
101      */
102     @Test
103     void testInvokeStatic4() throws Exception {
104         VThreadRunner.run(() -> {
105             Method foo = BadClass1.class.getDeclaredMethod("foo");
106             try {
107                 foo.invoke(null);
108                 fail();
109             } catch (ExceptionInInitializerError e) {
110                 assertTrue(e.getCause() instanceof ArithmeticException);
111             }
112         });
113     }
114 
115     static class BadClass1 {
116         static {
117             if (1==1) throw new ArithmeticException();
118         }
119         static void foo() { }
120     }
121 
122     /**
123      * Test that an error is thrown when invoking a static method triggers its
124      * class to be initialized and it fails with an error.
125      */
126     @Test
127     void testInvokeStatic5() throws Exception {
128         VThreadRunner.run(() -> {
129             Method foo = BadClass2.class.getDeclaredMethod("foo");
130             assertThrows(AbstractMethodError.class, () -> foo.invoke(null));
131         });
132     }
133 
134     static class BadClass2 {
135         static {
136             if (1==1) throw new AbstractMethodError();
137         }
138         static void foo() { }
139     }
140 
141     /**
142      * Test that invoking a static method does not pin the carrier thread.
143      */
144     @Test
145     void testInvokeStatic6() throws Exception {
146         assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
147         Method parkMethod = Parker.class.getDeclaredMethod("park");
148         try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
149             ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
150 
151             var ready = new CountDownLatch(1);
152             Thread vthread = factory.newThread(() -> {
153                 ready.countDown();
154                 try {
155                     parkMethod.invoke(null);   // blocks
156                 } catch (Exception e) { }
157             });
158             vthread.start();
159 
160             try {
161                 // wait for thread to run
162                 ready.await();
163 
164                 // unpark with another virtual thread, runs on same carrier thread
165                 Thread unparker = factory.newThread(() -> LockSupport.unpark(vthread));
166                 unparker.start();
167                 unparker.join();
168             } finally {
169                 LockSupport.unpark(vthread);  // in case test fails
170             }
171         }
172     }
173 
174     /**
175      * Test invoking instance method.
176      */
177     @Test
178     void testInvokeInstance1() throws Exception {
179         VThreadRunner.run(() -> {
180             var adder = new Adder();
181             Adder.addMethod().invoke(adder, 5);
182             assertTrue(adder.sum == 5);
183         });
184     }
185 
186     /**
187      * Test that InvocationTargetException is thrown when an instance method throws
188      * exception.
189      */
190     @Test
191     void testInvokeInstance2() throws Exception {
192         VThreadRunner.run(() -> {
193             var adder = new Adder();
194             try {
195                 Adder.addMethod().invoke(adder, -5);
196                 fail();
197             } catch (InvocationTargetException e) {
198                 assertTrue(e.getCause() instanceof IllegalArgumentException);
199             }
200         });
201     }
202 
203     /**
204      * Test that NullPointerException and IllegalArgumentException are thrown when
205      * trying to invoke an instance method with null or bad parameters.
206      */
207     @Test
208     void testInvokeInstance3() throws Exception {
209         VThreadRunner.run(() -> {
210             var adder = new Adder();
211             Method addMethod = Adder.addMethod();
212             assertThrows(NullPointerException.class,
213                     () -> addMethod.invoke(null));
214             assertThrows(IllegalArgumentException.class,
215                     () -> addMethod.invoke(adder));
216             assertThrows(IllegalArgumentException.class,
217                     () -> addMethod.invoke(adder, 1, 2));
218             assertThrows(IllegalArgumentException.class,
219                     () -> addMethod.invoke(adder, 1, "hi"));
220             assertThrows(IllegalArgumentException.class,
221                     () -> addMethod.invoke(adder, "hi"));
222         });
223     }
224 
225     /**
226      * Test invoking newInstance to create an object.
227      */
228     @Test
229     void testNewInstance1() throws Exception {
230         VThreadRunner.run(() -> {
231             Constructor<?> ctor = Adder.class.getDeclaredConstructor(long.class);
232             Adder adder = (Adder) ctor.newInstance(10);
233             assertTrue(adder.sum == 10);
234         });
235     }
236 
237     /**
238      * Test that InvocationTargetException is thrown when a constructor throws
239      * exception.
240      */
241     @Test
242     void testNewInstance2() throws Exception {
243         VThreadRunner.run(() -> {
244             Constructor<?> ctor = Adder.class.getDeclaredConstructor(long.class);
245             try {
246                 ctor.newInstance(-10);
247                 fail();
248             } catch (InvocationTargetException e) {
249                 assertTrue(e.getCause() instanceof IllegalArgumentException);
250             }
251         });
252     }
253 
254     /**
255      * Test that IllegalArgumentException is thrown when newInstacne is called
256      * with bad parameters.
257      */
258     @Test
259     void testNewInstance3() throws Exception {
260         VThreadRunner.run(() -> {
261             var adder = new Adder();
262             Constructor<?> ctor = Adder.class.getDeclaredConstructor(long.class);
263             assertThrows(IllegalArgumentException.class,
264                     () -> ctor.newInstance((Object[])null));
265             assertThrows(IllegalArgumentException.class,
266                     () -> ctor.newInstance(adder));
267             assertThrows(IllegalArgumentException.class,
268                     () -> ctor.newInstance(adder, null));
269             assertThrows(IllegalArgumentException.class,
270                     () -> ctor.newInstance(adder, "foo"));
271             assertThrows(IllegalArgumentException.class,
272                     () -> ctor.newInstance(adder, 1, 2));
273         });
274     }
275 
276     /**
277      * Test that ExceptionInInitializerError is thrown when invoking newInstance
278      * triggers the class to be initialized and it fails with exception.
279      */
280     @Test
281     void testNewInstance4() throws Exception {
282         VThreadRunner.run(() -> {
283             Constructor<?> ctor = BadClass3.class.getDeclaredConstructor();
284             try {
285                 ctor.newInstance((Object[])null);
286                 fail();
287             } catch (ExceptionInInitializerError e) {
288                 assertTrue(e.getCause() instanceof ArithmeticException);
289             }
290         });
291     }
292 
293     static class BadClass3 {
294         static {
295             if (1==1) throw new ArithmeticException();
296         }
297         static void foo() { }
298     }
299 
300     /**
301      * Test that error is thrown when invoking newInstance triggers the class
302      * to be initialized and it fails with an error.
303      */
304     @Test
305     void testNewInstance5() throws Exception {
306         VThreadRunner.run(() -> {
307             Constructor<?> ctor = BadClass4.class.getDeclaredConstructor();
308             assertThrows(AbstractMethodError.class, () -> ctor.newInstance((Object[])null));
309         });
310     }
311 
312     static class BadClass4 {
313         static {
314             if (1==1) throw new AbstractMethodError();
315         }
316         static void foo() { }
317     }
318 
319     /**
320      * Test that newInstance does not pin the carrier thread
321      */
322     @Test
323     void testNewInstance6() throws Exception {
324         assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
325         Constructor<?> ctor = Parker.class.getDeclaredConstructor();
326         try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
327             ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
328 
329             var ready = new CountDownLatch(1);
330             Thread vthread = factory.newThread(() -> {
331                 ready.countDown();
332                 try {
333                     ctor.newInstance();
334                 } catch (Exception e) { }
335             });
336             vthread.start();
337 
338             try {
339                 // wait for thread to run
340                 ready.await();
341 
342                 // unpark with another virtual thread, runs on same carrier thread
343                 Thread unparker = factory.newThread(() -> LockSupport.unpark(vthread));
344                 unparker.start();
345                 unparker.join();
346             } finally {
347                 LockSupport.unpark(vthread);  // in case test fails
348             }
349         }
350     }
351 
352 
353     // -- support classes and methods --
354 
355     static int divide(int x, int y) {
356         return x / y;
357     }
358 
359     static Method divideMethod() throws NoSuchMethodException {
360         return Reflection.class.getDeclaredMethod("divide", int.class, int.class);
361     }
362 
363     static class Adder {
364         long sum;
365         Adder() { }
366         Adder(long x) {
367             if (x < 0)
368                 throw new IllegalArgumentException();
369             sum = x;
370         }
371         Adder add(long x) {
372             if (x < 0)
373                 throw new IllegalArgumentException();
374             sum += x;
375             return this;
376         }
377         static Method addMethod() throws NoSuchMethodException {
378             return Adder.class.getDeclaredMethod("add", long.class);
379         }
380         long sum() {
381             return sum;
382         }
383     }
384 
385     static class Parker {
386         Parker() {
387             LockSupport.park();
388         }
389         static void park() {
390             LockSupport.park();
391         }
392     }
393 }