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 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.VThreadRunner;
 42 import org.junit.jupiter.api.Test;
 43 import static org.junit.jupiter.api.Assertions.*;
 44 import static org.junit.jupiter.api.Assumptions.*;
 45 
 46 class Reflection {
 47 
 48     /**
 49      * Test invoking static method.
 50      */
 51     @Test
 52     void testInvokeStatic1() throws Exception {
 53         VThreadRunner.run(() -> {
 54             int result = (int) divideMethod().invoke(null, 20, 2);
 55             assertTrue(result == 10);
 56         });
 57     }
 58 
 59     /**
 60      * Test that InvocationTargetException is thrown when a static method throws
 61      * exception.
 62      */
 63     @Test
 64     void testInvokeStatic2() throws Exception {
 65         VThreadRunner.run(() -> {
 66             try {
 67                 divideMethod().invoke(null, 20, 0);
 68                 fail();
 69             } catch (InvocationTargetException e) {
 70                 assertTrue(e.getCause() instanceof ArithmeticException);
 71             }
 72         });
 73     }
 74 
 75     /**
 76      * Test that IllegalArgumentException is thrown when trying to invoke a static
 77      * method with bad parameters.
 78      */
 79     @Test
 80     void testInvokeStatic3() throws Exception {
 81         VThreadRunner.run(() -> {
 82             assertThrows(IllegalArgumentException.class,
 83                     () -> divideMethod().invoke(null));
 84             assertThrows(IllegalArgumentException.class,
 85                     () -> divideMethod().invoke(null, 1));
 86             assertThrows(IllegalArgumentException.class,
 87                     () -> divideMethod().invoke(null, 1, 2, 3));
 88             assertThrows(IllegalArgumentException.class,
 89                     () -> divideMethod().invoke(new Object()));
 90             assertThrows(IllegalArgumentException.class,
 91                     () -> divideMethod().invoke(new Object(), 1));
 92             assertThrows(IllegalArgumentException.class,
 93                     () -> divideMethod().invoke(new Object(), 1, 2, 3));
 94         });
 95     }
 96 
 97     /**
 98      * Test that ExceptionInInitializerError is thrown when invoking a static
 99      * method triggers its class to be initialized and it fails with exception.
100      */
101     @Test
102     void testInvokeStatic4() throws Exception {
103         VThreadRunner.run(() -> {
104             Method foo = BadClass1.class.getDeclaredMethod("foo");
105             try {
106                 foo.invoke(null);
107                 fail();
108             } catch (ExceptionInInitializerError e) {
109                 assertTrue(e.getCause() instanceof ArithmeticException);
110             }
111         });
112     }
113 
114     static class BadClass1 {
115         static {
116             if (1==1) throw new ArithmeticException();
117         }
118         static void foo() { }
119     }
120 
121     /**
122      * Test that an error is thrown when invoking a static method triggers its
123      * class to be initialized and it fails with an error.
124      */
125     @Test
126     void testInvokeStatic5() throws Exception {
127         VThreadRunner.run(() -> {
128             Method foo = BadClass2.class.getDeclaredMethod("foo");
129             assertThrows(AbstractMethodError.class, () -> foo.invoke(null));
130         });
131     }
132 
133     static class BadClass2 {
134         static {
135             if (1==1) throw new AbstractMethodError();
136         }
137         static void foo() { }
138     }
139 
140     /**
141      * Test that invoking a static method does not pin the carrier thread.
142      */
143     @Test
144     void testInvokeStatic6() throws Exception {
145         assumeTrue(ThreadBuilders.supportsCustomScheduler(), "No support for custom schedulers");
146         Method parkMethod = Parker.class.getDeclaredMethod("park");
147         try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
148             Thread.Builder builder = ThreadBuilders.virtualThreadBuilder(scheduler);
149             ThreadFactory factory = builder.factory();
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(ThreadBuilders.supportsCustomScheduler(), "No support for custom schedulers");
325         Constructor<?> ctor = Parker.class.getDeclaredConstructor();
326         try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
327             Thread.Builder builder = ThreadBuilders.virtualThreadBuilder(scheduler);
328             ThreadFactory factory = builder.factory();
329 
330             var ready = new CountDownLatch(1);
331             Thread vthread = factory.newThread(() -> {
332                 ready.countDown();
333                 try {
334                     ctor.newInstance();
335                 } catch (Exception e) { }
336             });
337             vthread.start();
338 
339             try {
340                 // wait for thread to run
341                 ready.await();
342 
343                 // unpark with another virtual thread, runs on same carrier thread
344                 Thread unparker = factory.newThread(() -> LockSupport.unpark(vthread));
345                 unparker.start();
346                 unparker.join();
347             } finally {
348                 LockSupport.unpark(vthread);  // in case test fails
349             }
350         }
351     }
352 
353 
354     // -- support classes and methods --
355 
356     static int divide(int x, int y) {
357         return x / y;
358     }
359 
360     static Method divideMethod() throws NoSuchMethodException {
361         return Reflection.class.getDeclaredMethod("divide", int.class, int.class);
362     }
363 
364     static class Adder {
365         long sum;
366         Adder() { }
367         Adder(long x) {
368             if (x < 0)
369                 throw new IllegalArgumentException();
370             sum = x;
371         }
372         Adder add(long x) {
373             if (x < 0)
374                 throw new IllegalArgumentException();
375             sum += x;
376             return this;
377         }
378         static Method addMethod() throws NoSuchMethodException {
379             return Adder.class.getDeclaredMethod("add", long.class);
380         }
381         long sum() {
382             return sum;
383         }
384     }
385 
386     static class Parker {
387         Parker() {
388             LockSupport.park();
389         }
390         static void park() {
391             LockSupport.park();
392         }
393     }
394 }