< prev index next >

test/jdk/java/lang/management/ThreadMXBean/VirtualThreads.java

Print this page

  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  */

 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)

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);

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 }

  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  */

 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.nio.channels.Selector;
 45 import java.util.Arrays;
 46 import java.util.Set;
 47 import java.util.concurrent.Executor;
 48 import java.util.concurrent.ExecutorService;
 49 import java.util.concurrent.Executors;
 50 import java.util.concurrent.ThreadFactory;
 51 import java.util.concurrent.atomic.AtomicReference;
 52 import java.util.concurrent.locks.LockSupport;
 53 import java.util.stream.Collectors;
 54 
 55 import jdk.test.lib.thread.VThreadPinner;
 56 import jdk.test.lib.thread.VThreadRunner;
 57 import jdk.test.lib.thread.VThreadScheduler;
 58 import org.junit.jupiter.api.Test;
 59 import org.junit.jupiter.params.ParameterizedTest;
 60 import org.junit.jupiter.params.provider.ValueSource;
 61 import static org.junit.jupiter.api.Assertions.*;
 62 import static org.junit.jupiter.api.Assumptions.*;
 63 
 64 public class VirtualThreads {
 65 
 66     /**
 67      * Test that ThreadMXBean.dumpAllThreads does not include virtual threads.
 68      */
 69     @ParameterizedTest
 70     @ValueSource(ints = {0, Integer.MAX_VALUE})
 71     void testDumpAllThreads(int maxDepth) {
 72         Thread vthread = Thread.startVirtualThread(LockSupport::park);
 73         try {
 74             ThreadMXBean bean = ManagementFactory.getThreadMXBean();
 75             ThreadInfo[] infos = bean.dumpAllThreads(false, false, maxDepth);
 76             Set<Long> tids = Arrays.stream(infos)
 77                     .map(ThreadInfo::getThreadId)

179             long[] tids = new long[] { tid0, tid1 };
180             ThreadMXBean bean = ManagementFactory.getThreadMXBean();
181             ThreadInfo[] infos = bean.getThreadInfo(tids, false, false, maxDepth);
182             if (Thread.currentThread().isVirtual()) {
183                 assertNull(infos[0]);
184             } else {
185                 assertEquals(tid0, infos[0].getThreadId());
186             }
187             assertNull(infos[1]);
188         } finally {
189             LockSupport.unpark(vthread);
190         }
191     }
192 
193     /**
194      * Test ThreadMXBean.getThreadInfo(long) with the thread id of a carrier thread.
195      * The stack frames of the virtual thread should not be returned.
196      */
197     @Test
198     void testGetThreadInfoCarrierThread() throws Exception {
199         assumeTrue(VThreadScheduler.supportsCustomScheduler(), "No support for custom schedulers");
200         try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
201             var carrierRef = new AtomicReference<Thread>();
202             Executor scheduler = (task) -> {
203                 pool.execute(() -> {
204                     carrierRef.set(Thread.currentThread());
205                     task.run();
206                 });
207             };
208             ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
209 
210             // start virtual thread so carrier Thread can be captured
211             Thread thread = factory.newThread(() -> { });
212             thread.start();
213             thread.join();
214             Thread carrier = carrierRef.get();
215             assertTrue(carrier != null && !carrier.isVirtual());
216 
217             try (Selector sel = Selector.open()) {
218                 String selClassName = sel.getClass().getName();
219 
220                 // start virtual thread that blocks while pinned
221                 Thread vthread = factory.newThread(() -> {
222                     try {
223                         VThreadPinner.runPinned(sel::select);
224                     } catch (Exception e) { }
225                 });
226                 vthread.start();
227 
228                 // wait for virtual thread to block in select
229                 while (!contains(vthread.getStackTrace(), selClassName)) {
230                     Thread.sleep(20);
231                 }
232 
233                 // invoke getThreadInfo get and check the stack trace
234                 long tid = carrier.getId();
235                 ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(tid, 100);
236 
237                 // should only see carrier frames
238                 StackTraceElement[] stack = info.getStackTrace();
239                 assertTrue(contains(stack, "java.util.concurrent.ThreadPoolExecutor"));
240                 assertFalse(contains(stack, selClassName));
241 
242                 // carrier should not be holding any monitors
243                 assertEquals(0, info.getLockedMonitors().length);
244             }
245         }
246     }
247 
248     /**
249      * Test that ThreadMXBean.getThreadCpuTime(long) returns -1 for a virtual thread.
250      */
251     @Test
252     void testGetThreadCpuTime1() {
253         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
254         assumeTrue(bean.isThreadCpuTimeSupported(), "Thread CPU time measurement not supported");
255 
256         Thread vthread = Thread.startVirtualThread(LockSupport::park);
257         try {
258             long tid = vthread.threadId();
259             long cpuTime = bean.getThreadCpuTime(tid);
260             assertEquals(-1L, cpuTime);

346     /**
347      * Test that ThreadMXBean::getCurrentThreadUserTime returns -1 when invoked
348      * from a virtual thread.
349      */
350     @Test
351     void testGetCurrentThreadUserTime() throws Exception {
352         ThreadMXBean bean = ManagementFactory.getThreadMXBean();
353         assumeTrue(bean.isCurrentThreadCpuTimeSupported(),
354                 "Thread CPU time measurement for the current thread not supported");
355 
356         VThreadRunner.run(() -> {
357             assertEquals(-1L, bean.getCurrentThreadUserTime());
358         });
359     }
360 
361     private static boolean contains(StackTraceElement[] stack, String className) {
362         return Arrays.stream(stack)
363                 .map(StackTraceElement::getClassName)
364                 .anyMatch(className::equals);
365     }




































366 }
< prev index next >