milamberspace commented on code in PR #6855: URL: https://github.com/apache/jmeter/pull/6855#discussion_r4731679193
########## src/core/src/main/java/org/apache/jmeter/threads/JMeterThreadFactory.java: ########## @@ -0,0 +1,171 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.threads; + +import java.lang.reflect.Method; + +import org.apache.jmeter.util.JMeterUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Creates the {@link Thread} instances that run {@link JMeterThread}s. + * + * <p>By default this creates ordinary platform threads, exactly as JMeter has always done. + * When the property {@value #USE_VIRTUAL_THREADS_PROPERTY} is set to {@code true} and the + * JVM supports virtual threads (Java 21+), the user threads are created as virtual threads + * instead. One dedicated thread is still created per {@code JMeterThread}: threads are never + * pooled or shared between virtual users, so {@code ThreadLocal}-based state (for instance + * {@link JMeterContextService}) keeps its current semantics.</p> + * + * <p>JMeter is compiled for Java 17, so the Java 21 virtual-thread APIs + * ({@code Thread.ofVirtual()}, {@code Thread.isVirtual()}) are accessed reflectively. + * On Java 17, or when reflective creation fails (for instance on a preview runtime + * without {@code --enable-preview}), the factory silently falls back to platform threads, + * apart from a one-time warning.</p> + * + * <p>Note that virtual threads are always daemon threads, and a virtual thread that holds + * a monitor while performing blocking I/O may pin its carrier thread on Java 21. + * That is one of the reasons this feature is opt-in.</p> + */ +public final class JMeterThreadFactory { + + private static final Logger log = LoggerFactory.getLogger(JMeterThreadFactory.class); + + /** Property that enables running JMeter user threads on virtual threads. */ + public static final String USE_VIRTUAL_THREADS_PROPERTY = "jmeterthread.use_virtual_threads"; // $NON-NLS-1$ + + // Reflective handles for the Java 21 virtual thread API, null when unavailable. + private static final Method OF_VIRTUAL_METHOD = lookupOfVirtualMethod(); + private static final Method BUILDER_NAME_METHOD = lookupBuilderMethod("name", String.class); // $NON-NLS-1$ + private static final Method BUILDER_UNSTARTED_METHOD = lookupBuilderMethod("unstarted", Runnable.class); // $NON-NLS-1$ + private static final Method IS_VIRTUAL_METHOD = lookupIsVirtualMethod(); + + private static volatile boolean warnedVirtualThreadsUnavailable; + + private JMeterThreadFactory() { + // utility class + } + + /** + * @return {@code true} when the opt-in property is set. Read dynamically on purpose: + * thread creation is not a hot path, and dynamic reads keep tests and GUI + * property changes simple. + */ + public static boolean isVirtualThreadsEnabled() { + return JMeterUtils.getPropDefault(USE_VIRTUAL_THREADS_PROPERTY, false); + } + + /** + * @return {@code true} when the current JVM offers the Java 21 virtual thread API. + */ + public static boolean isVirtualThreadsSupported() { + return OF_VIRTUAL_METHOD != null && BUILDER_NAME_METHOD != null && BUILDER_UNSTARTED_METHOD != null; + } + + /** + * Creates an unstarted thread for the given workload. + * + * @param runnable the workload, typically a {@link JMeterThread} + * @param name the thread name, preserved for both platform and virtual threads + * @return an unstarted platform thread, or an unstarted virtual thread when virtual + * threads are enabled, supported, and creation succeeds + */ + public static Thread newThread(Runnable runnable, String name) { + if (isVirtualThreadsEnabled()) { + Thread virtualThread = newVirtualThread(runnable, name); + if (virtualThread != null) { + return virtualThread; + } + } + return new Thread(runnable, name); + } + + /** + * Reflective {@code Thread.isVirtual()} that also works when running on Java 17. + * + * @param thread the thread to inspect + * @return {@code true} when the thread is a virtual thread, {@code false} otherwise + * (including on JVMs without virtual thread support) + */ + public static boolean isVirtual(Thread thread) { + if (thread == null || IS_VIRTUAL_METHOD == null) { + return false; + } + try { + return Boolean.TRUE.equals(IS_VIRTUAL_METHOD.invoke(thread)); + } catch (ReflectiveOperationException | RuntimeException e) { + return false; + } + } + + private static Thread newVirtualThread(Runnable runnable, String name) { + if (!isVirtualThreadsSupported()) { + warnUnavailableOnce(); + return null; + } + try { + Object builder = OF_VIRTUAL_METHOD.invoke(null); + Object namedBuilder = BUILDER_NAME_METHOD.invoke(builder, name); + return (Thread) BUILDER_UNSTARTED_METHOD.invoke(namedBuilder, runnable); + } catch (ReflectiveOperationException | RuntimeException e) { + // For instance, virtual threads are a preview feature on Java 19/20 and + // creating one without --enable-preview fails. Fall back to a platform thread. + if (log.isWarnEnabled()) { + log.warn("Could not create a virtual thread, falling back to a platform thread", e); Review Comment: If creation fails systematically (for instance Java 19/20 without `--enable-preview`), this logs a warning with a stack trace for every user thread: 2000 users means 2000 stack traces. Logging once, like `warnUnavailableOnce()`, would be enough. ########## src/core/src/test/java/org/apache/jmeter/threads/TestJMeterThreadFactory.java: ########## @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.threads; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.jmeter.junit.JMeterTestCase; +import org.apache.jmeter.util.JMeterUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class TestJMeterThreadFactory extends JMeterTestCase { Review Comment: This test changes `jmeterthread.use_virtual_threads`, a global JMeter property, while other tests may run in parallel; a concurrent `ThreadGroup` test could then get virtual threads. Please mark it serial: ```suggestion class TestJMeterThreadFactory extends JMeterTestCase implements JMeterSerialTest { ``` (plus `import org.apache.jorphan.test.JMeterSerialTest;`). ########## src/core/src/main/java/org/apache/jmeter/threads/JMeterThreadFactory.java: ########## @@ -0,0 +1,171 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.threads; + +import java.lang.reflect.Method; + +import org.apache.jmeter.util.JMeterUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Creates the {@link Thread} instances that run {@link JMeterThread}s. + * + * <p>By default this creates ordinary platform threads, exactly as JMeter has always done. + * When the property {@value #USE_VIRTUAL_THREADS_PROPERTY} is set to {@code true} and the + * JVM supports virtual threads (Java 21+), the user threads are created as virtual threads + * instead. One dedicated thread is still created per {@code JMeterThread}: threads are never + * pooled or shared between virtual users, so {@code ThreadLocal}-based state (for instance + * {@link JMeterContextService}) keeps its current semantics.</p> + * + * <p>JMeter is compiled for Java 17, so the Java 21 virtual-thread APIs + * ({@code Thread.ofVirtual()}, {@code Thread.isVirtual()}) are accessed reflectively. + * On Java 17, or when reflective creation fails (for instance on a preview runtime + * without {@code --enable-preview}), the factory silently falls back to platform threads, + * apart from a one-time warning.</p> + * + * <p>Note that virtual threads are always daemon threads, and a virtual thread that holds + * a monitor while performing blocking I/O may pin its carrier thread on Java 21. + * That is one of the reasons this feature is opt-in.</p> + */ +public final class JMeterThreadFactory { Review Comment: Does this need to be public? It adds a public API in `core`; package-private would be enough since `ThreadGroup` is in the same package. ########## bin/jmeter.properties: ########## @@ -1241,6 +1241,16 @@ cookies=cookies # How often to check for shutdown during ramp-up (milliseconds) #jmeterthread.rampup.granularity=1000 +# Run JMeter user threads (one per virtual user) on Java 21 virtual threads instead of +# platform (OS) threads. This can substantially reduce thread memory and context-switching +# overhead for tests whose user threads mostly wait (HTTP responses, timers, JDBC), allowing +# more concurrent virtual users per load generator. It does not speed up CPU-bound samplers. +# Requires Java 21+; on older JVMs the setting is ignored and platform threads are used. +# Disabled by default. Note: virtual threads are always daemon threads, and on Java 21 a +# virtual thread that holds a monitor (synchronized) while blocking may pin its carrier +# thread; watch for jdk.VirtualThreadPinned events in JFR when enabling this. +#jmeterthread.use_virtual_threads=false Review Comment: Could the comment also mention: - the measurement bias: virtual threads are not time-sliced, so CPU-heavy samplers or post-processors (JSR223, regex/JSON extraction on large responses) can delay other users and inflate the measured response times, and pinning on Java 21 makes it worse; - that only `ThreadGroup` (and setUp/tearDown) honor the property, not `OpenModelThreadGroup`; - that JMeter's thread dumps (`ThreadDump`, `jmeter.exit.check.pause`) do not show virtual threads; use `jcmd <pid> Thread.dump_to_file -format=json` instead. ########## src/core/src/main/java/org/apache/jmeter/threads/ThreadGroup.java: ########## @@ -587,8 +587,13 @@ public void run() { jmThread.setScheduled(true); jmThread.setEndTime(endtime); } - Thread newThread = new Thread(jmThread, jmThread.getThreadName()); - newThread.setDaemon(false); // ThreadStarter is daemon, but we don't want sampler threads to be so too + Thread newThread = JMeterThreadFactory.newThread(jmThread, jmThread.getThreadName()); + // Virtual threads are always daemon threads, and setDaemon(false) is not legal for them. + // The engine waits for user threads explicitly (see waitThreadsStopped), so it does not + // rely on user threads being non-daemon to keep the JVM alive. + if (!JMeterThreadFactory.isVirtual(newThread)) { Review Comment: Minor: the reflective `isVirtual()` is only used to avoid `setDaemon(false)`. `if (newThread.isDaemon())` would achieve the same without reflection, since virtual threads always report `isDaemon() == true` and a platform thread created by a daemon `ThreadStarter` inherits the daemon flag. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
