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 id=default
 26  * @bug 8284161 8290562 8303242
 27  * @summary Test java.lang.management.ThreadMXBean with virtual threads
 28  * @modules java.base/java.lang:+open java.management
 29  * @library /test/lib
 30  * @run junit/othervm VirtualThreads
 31  */
 32 
 33 /**
 34  * @test id=no-vmcontinuations
 35  * @requires vm.continuations
 36  * @modules java.base/java.lang:+open java.management
 37  * @library /test/lib
 38  * @run junit/othervm -XX:+UnlockExperimentalVMOptions -XX:-VMContinuations VirtualThreads
 39  */
 40 
 41 import java.lang.management.ManagementFactory;
 42 import java.lang.management.ThreadInfo;
 43 import java.lang.management.ThreadMXBean;
 44 import java.lang.reflect.Constructor;
 45 import java.lang.reflect.InvocationTargetException;
 46 import java.nio.channels.Selector;
 47 import java.util.Arrays;
 48 import java.util.Set;
 49 import java.util.concurrent.Executor;
 50 import java.util.concurrent.ExecutorService;
 51 import java.util.concurrent.Executors;
 52 import java.util.concurrent.atomic.AtomicReference;
 53 import java.util.concurrent.locks.LockSupport;
 54 import java.util.stream.Collectors;
 55 
 56 import jdk.test.lib.thread.VThreadRunner;
 57 import org.junit.jupiter.api.Test;
 58 import org.junit.jupiter.params.ParameterizedTest;
 59 import org.junit.jupiter.params.provider.ValueSource;
 60 import static org.junit.jupiter.api.Assertions.*;
 61 import static org.junit.jupiter.api.Assumptions.*;
 62 
 63 public class VirtualThreads {
 64 
 65     /**
 66      * Test that ThreadMXBean.dumpAllThreads does not include virtual threads.
 67      */
 68     @ParameterizedTest
 69     @ValueSource(ints = {0, Integer.MAX_VALUE})
 70     void testDumpAllThreads(int maxDepth) {
 71         Thread vthread = Thread.startVirtualThread(LockSupport::park);
 72         try {
 73             ThreadMXBean bean = ManagementFactory.getThreadMXBean();
 74             ThreadInfo[] infos = bean.dumpAllThreads(false, false, maxDepth);
 75             Set<Long> tids = Arrays.stream(infos)
 76                     .map(ThreadInfo::getThreadId)
 77                     .collect(Collectors.toSet());
 78 
 79             // if current thread is a platform thread then it should be included
 80             boolean expected = !Thread.currentThread().isVirtual();
 81             assertEquals(expected, tids.contains(Thread.currentThread().threadId()));
 82 
 83             // virtual thread should not be included
 84             assertFalse(tids.contains(vthread.threadId()));
 85         } finally {
 86             LockSupport.unpark(vthread);
 87         }
 88     }
 89 
 90     /**
 91      * Test that ThreadMXBean::getAllThreadsIds does not include virtual threads.
 92      */
 93     @Test
 94     void testGetAllThreadIds() {
 95         Thread vthread = Thread.startVirtualThread(LockSupport::park);
 96         try {
 97             long[] tids = ManagementFactory.getThreadMXBean().getAllThreadIds();
 98 
 99             // if current thread is a platform thread then it should be included
100             boolean expected = !Thread.currentThread().isVirtual();
101             long currentTid = Thread.currentThread().threadId();
102             assertEquals(expected, Arrays.stream(tids).anyMatch(tid -> tid == currentTid));
103 
104             // virtual thread should not be included
105             long vtid = vthread.threadId();
106             assertFalse(Arrays.stream(tids).anyMatch(tid -> tid == vtid));
107         } finally {
108             LockSupport.unpark(vthread);
109         }
110     }
111 
112     /**
113      * Test that ThreadMXBean.getThreadInfo(long, maxDepth) returns null for a virtual
114      * thread.
115      */
116     @ParameterizedTest
117     @ValueSource(ints = {0, Integer.MAX_VALUE})
118     void testGetThreadInfo1(int maxDepth) {
119         Thread vthread = Thread.startVirtualThread(LockSupport::park);
120         try {
121             long tid = vthread.threadId();
122             ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(tid, maxDepth);
123             assertNull(info);
124         } finally {
125             LockSupport.unpark(vthread);
126         }
127     }
128 
129     /**
130      * Test that ThreadMXBean.getThreadInfo(long, maxDepth) returns null when invoked
131      * by a virtual thread with its own thread id.
132      */
133     @ParameterizedTest
134     @ValueSource(ints = {0, Integer.MAX_VALUE})
135     void testGetThreadInfo2(int maxDepth) throws Exception {
136         VThreadRunner.run(() -> {
137             long tid = Thread.currentThread().threadId();
138             ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(tid, maxDepth);
139             assertNull(info);
140         });
141     }
142 
143     /**
144      * Test that ThreadMXBean.getThreadInfo(long[], maxDepth) returns a null ThreadInfo
145      * for elements that correspond to a virtual thread.
146      */
147     @ParameterizedTest
148     @ValueSource(ints = {0, Integer.MAX_VALUE})
149     void testGetThreadInfo3(int maxDepth) {
150         Thread vthread = Thread.startVirtualThread(LockSupport::park);
151         try {
152             long tid0 = Thread.currentThread().threadId();
153             long tid1 = vthread.threadId();
154             long[] tids = new long[] { tid0, tid1 };
155             ThreadInfo[] infos = ManagementFactory.getThreadMXBean().getThreadInfo(tids, maxDepth);
156             if (Thread.currentThread().isVirtual()) {
157                 assertNull(infos[0]);
158             } else {
159                 assertEquals(tid0, infos[0].getThreadId());
160             }
161             assertNull(infos[1]);
162         } finally {
163             LockSupport.unpark(vthread);
164         }
165     }
166 
167     /**
168      * Test that ThreadMXBean.getThreadInfo(long[], boolean, boolean, maxDepth) returns
169      * a null ThreadInfo for elements that correspond to a virtual thread.
170      */
171     @ParameterizedTest
172     @ValueSource(ints = {0, Integer.MAX_VALUE})
173     void testGetThreadInfo4(int maxDepth) {
174         Thread vthread = Thread.startVirtualThread(LockSupport::park);
175         try {
176             long tid0 = Thread.currentThread().threadId();
177             long tid1 = vthread.threadId();
178             long[] tids = new long[] { tid0, tid1 };
179             ThreadMXBean bean = ManagementFactory.getThreadMXBean();
180             ThreadInfo[] infos = bean.getThreadInfo(tids, false, false, maxDepth);
181             if (Thread.currentThread().isVirtual()) {
182                 assertNull(infos[0]);
183             } else {
184                 assertEquals(tid0, infos[0].getThreadId());
185             }
186             assertNull(infos[1]);
187         } finally {
188             LockSupport.unpark(vthread);
189         }
190     }
191 
192     /**
193      * Test ThreadMXBean.getThreadInfo(long) with the thread id of a carrier thread.
194      * The stack frames of the virtual thread should not be returned.
195      */
196     @Test
197     void testGetThreadInfoCarrierThread() throws Exception {
198         assumeTrue(supportsCustomScheduler(), "No support for custom schedulers");
199         try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
200             var carrierRef = new AtomicReference<Thread>();
201             Executor scheduler = (task) -> {
202                 pool.execute(() -> {
203                     carrierRef.set(Thread.currentThread());
204                     task.run();
205                 });
206             };
207 
208             // start virtual thread so carrier Thread can be captured
209             virtualThreadBuilder(scheduler).start(() -> { }).join();
210             Thread carrier = carrierRef.get();
211             assertTrue(carrier != null && !carrier.isVirtual());
212 
213             try (Selector sel = Selector.open()) {
214                 // start virtual thread that blocks in a native method
215                 virtualThreadBuilder(scheduler).start(() -> {
216                     try {
217                         sel.select();
218                     } catch (Exception e) { }
219                 });
220 
221                 // invoke getThreadInfo get and check the stack trace
222                 long tid = carrier.getId();
223                 ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(tid, 100);
224 
225                 // should only see carrier frames
226                 StackTraceElement[] stack = info.getStackTrace();
227                 assertTrue(contains(stack, "java.util.concurrent.ThreadPoolExecutor"));
228                 assertFalse(contains(stack, "java.nio.channels.Selector"));
229 
230                 // carrier should not be holding any monitors
231                 assertEquals(0, info.getLockedMonitors().length);
232             }
233         }
234     }
235 
236     /**
237      * Test that ThreadMXBean.getThreadCpuTime(long) returns -1 for a virtual thread.
238      */
239     @Test
240     void testGetThreadCpuTime1() {
241         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
242         assumeTrue(bean.isThreadCpuTimeSupported(), "Thread CPU time measurement not supported");
243 
244         Thread vthread = Thread.startVirtualThread(LockSupport::park);
245         try {
246             long tid = vthread.threadId();
247             long cpuTime = bean.getThreadCpuTime(tid);
248             assertEquals(-1L, cpuTime);
249         } finally {
250             LockSupport.unpark(vthread);
251         }
252     }
253 
254     /**
255      * Test that ThreadMXBean.getThreadCpuTime(long) returns -1 when invoked by a
256      * virtual thread with its own thread id.
257      */
258     @Test
259     void testGetThreadCpuTime2() throws Exception {
260         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
261         assumeTrue(bean.isThreadCpuTimeSupported(), "Thread CPU time measurement not supported");
262 
263         VThreadRunner.run(() -> {
264             long tid = Thread.currentThread().threadId();
265             long cpuTime = bean.getThreadCpuTime(tid);
266             assertEquals(-1L, cpuTime);
267         });
268     }
269 
270     /**
271      * Test that ThreadMXBean.getThreadUserTime(long) returns -1 for a virtual thread.
272      */
273     @Test
274     void testGetThreadUserTime1() {
275         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
276         assumeTrue(bean.isThreadCpuTimeSupported(), "Thread CPU time measurement not supported");
277 
278         Thread vthread = Thread.startVirtualThread(LockSupport::park);
279         try {
280             long tid = vthread.threadId();
281             long userTime = ManagementFactory.getThreadMXBean().getThreadUserTime(tid);
282             assertEquals(-1L, userTime);
283         } finally {
284             LockSupport.unpark(vthread);
285         }
286     }
287 
288     /**
289      * Test that ThreadMXBean.getThreadUserTime(long) returns -1 when invoked by a
290      * virtual thread with its own thread id.
291      */
292     @Test
293     void testGetThreadUserTime2() throws Exception {
294         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
295         assumeTrue(bean.isThreadCpuTimeSupported(), "Thread CPU time measurement not supported");
296 
297         VThreadRunner.run(() -> {
298             long tid = Thread.currentThread().threadId();
299             long userTime = ManagementFactory.getThreadMXBean().getThreadUserTime(tid);
300             assertEquals(-1L, userTime);
301         });
302     }
303 
304     /**
305      * Test that ThreadMXBean::isCurrentThreadCpuTimeSupported returns true when
306      * CPU time measurement for the current thread is supported.
307      */
308     @Test
309     void testIsCurrentThreadCpuTimeSupported() throws Exception {
310         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
311         assumeTrue(bean.isCurrentThreadCpuTimeSupported(),
312                 "Thread CPU time measurement for the current thread not supported");
313 
314         VThreadRunner.run(() -> {
315             assertTrue(bean.isCurrentThreadCpuTimeSupported());
316         });
317     }
318 
319     /**
320      * Test that ThreadMXBean::getCurrentThreadCpuTime returns -1 when invoked
321      * from a virtual thread.
322      */
323     @Test
324     void testGetCurrentThreadCpuTime() throws Exception {
325         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
326         assumeTrue(bean.isCurrentThreadCpuTimeSupported(),
327                 "Thread CPU time measurement for the current thread not supported");
328 
329         VThreadRunner.run(() -> {
330             assertEquals(-1L, bean.getCurrentThreadCpuTime());
331         });
332     }
333 
334     /**
335      * Test that ThreadMXBean::getCurrentThreadUserTime returns -1 when invoked
336      * from a virtual thread.
337      */
338     @Test
339     void testGetCurrentThreadUserTime() throws Exception {
340         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
341         assumeTrue(bean.isCurrentThreadCpuTimeSupported(),
342                 "Thread CPU time measurement for the current thread not supported");
343 
344         VThreadRunner.run(() -> {
345             assertEquals(-1L, bean.getCurrentThreadUserTime());
346         });
347     }
348 
349     private static boolean contains(StackTraceElement[] stack, String className) {
350         return Arrays.stream(stack)
351                 .map(StackTraceElement::getClassName)
352                 .anyMatch(className::equals);
353     }
354 
355     /**
356      * Returns a builder to create virtual threads that use the given scheduler.
357      * @throws UnsupportedOperationException if there is no support for custom schedulers
358      */
359     private static Thread.Builder.OfVirtual virtualThreadBuilder(Executor scheduler) {
360         Thread.Builder.OfVirtual builder = Thread.ofVirtual();
361         try {
362             Class<?> clazz = Class.forName("java.lang.ThreadBuilders$VirtualThreadBuilder");
363             Constructor<?> ctor = clazz.getDeclaredConstructor(Executor.class);
364             ctor.setAccessible(true);
365             return (Thread.Builder.OfVirtual) ctor.newInstance(scheduler);
366         } catch (InvocationTargetException e) {
367             Throwable cause = e.getCause();
368             if (cause instanceof RuntimeException re) {
369                 throw re;
370             }
371             throw new RuntimeException(e);
372         } catch (Exception e) {
373             throw new RuntimeException(e);
374         }
375     }
376 
377     /**
378      * Return true if custom schedulers are supported.
379      */
380     private static boolean supportsCustomScheduler() {
381         try (var pool = Executors.newCachedThreadPool()) {
382             try {
383                 virtualThreadBuilder(pool);
384                 return true;
385             } catch (UnsupportedOperationException e) {
386                 return false;
387             }
388         }
389     }
390 }