Skip to content
Being BE
Go back

Contributing to Jetty, Part 2: Real Server Tests, Writing the Docs, and Opening the PR

—viewsEdit page
On this page

I shared my intermediate results on the issue but got no feedback, and since it had the help-wanted label anyway, I decided to just open a PR!

First, before opening the PR, I had to finish the remaining work. I had already finished all the related tests earlier, but I hadn’t done the real server test or the documentation, so I had to get those done

GitHub Repository
Eclipse Jetty
jetty/jetty.project

A Java-based web server and servlet container

View on GitHub
Eclipse Jetty GitHub repository preview
Contributing to Jetty Series

Part 1 · Exploring and Verifying the Virtual Thread Creation Limit Issue

Part 2 · Real Server Tests, Writing the Docs, and Opening the PR


Adding a Test That Checks the Behavior on a Real Server

// JDK 20 and below have no virtual threads, so the test is skipped
@DisabledForJreRange(max = JRE.JAVA_20)
public class QueuedThreadPoolVirtualThreadServerTest
{
    // Maximum number of threads the thread pool can create
    private static final int MAX_THREADS = 16;
    // Number of HTTP requests sent at the same time. It has to be much larger than the cap (16) to see "whether the cap blocks it"
    private static final int REQUESTS = 100;

    private Server server;

    // jetty is compiled against Java 17, so this API can't be used directly → work around it with reflection
    private static ThreadFactory virtualThreadFactory() throws Exception
    {
        Object builder = Thread.class.getMethod("ofVirtual").invoke(null);
        Class<?> builderClass = Class.forName("java.lang.Thread$Builder");
        return (ThreadFactory)builderClass.getMethod("factory").invoke(builder);
    }

    @AfterEach
    public void dispose()
    {
        LifeCycle.stop(server);
    }

    @Test
    public void testServerServesRequestsOnCappedVirtualThreads() throws Exception
    {
        // ───────────── 1. Prepare the thread pool ─────────────
        QueuedThreadPool qtp = new QueuedThreadPool(MAX_THREADS, 1, 60_000, 0, null, null, virtualThreadFactory());

        // ───────────── 2. Prepare the server ─────────────
        server = new Server(qtp);
        // 1 acceptor (accepts new connections) + 1 selector (watches which connection has data)
        // These two also each keep occupying one qtp thread → only 16 - 2 = 14 are available for handling requests
        ServerConnector connector = new ServerConnector(server, 1, 1);
        server.addConnector(connector);

        // ───────────── 3. Variables for measurement ─────────────
        // Several threads touch these at the same time, so use Atomic
        AtomicInteger active = new AtomicInteger();            // Number of requests currently being handled inside the Handler
        AtomicInteger peakActive = new AtomicInteger();        // The maximum of that value (peak concurrent handling)
        AtomicInteger peakPoolThreads = new AtomicInteger();   // The maximum number of threads the pool created
        AtomicBoolean nonVirtualHandlerThread = new AtomicBoolean(); // Whether a request was ever handled somewhere other than a virtual thread

        // ───────────── 4. Request handling Handler ─────────────
        // Jetty 12 core API instead of a Servlet. Every time a request comes in, handle() runs on a pool thread
        server.setHandler(new Handler.Abstract()
        {
            @Override
            public boolean handle(Request request, Response response, Callback callback) throws Exception
            {
                // (Check A) Whether the thread running this code right now is a virtual thread
                if (!VirtualThreads.isVirtualThread())
                    nonVirtualHandlerThread.set(true);

                // It came in, so active +1, and if that value is the highest so far, update peakActive
                peakActive.accumulateAndGet(active.incrementAndGet(), Math::max);
                // Record the number of threads the pool has created at this moment (keeping the maximum)
                peakPoolThreads.accumulateAndGet(qtp.getThreads(), Math::max);
                try
                {
                    // Deliberately block for 50ms (imitating a slow task like a DB query)
                    // If requests finish too quickly, they don't overlap, so the cap can't be tested
                    Thread.sleep(50);
                }
                finally
                {
                    // Done handling → active -1
                    active.decrementAndGet();
                }
                // Response: 200 + body "ok"
                response.setStatus(200);
                Content.Sink.write(response, true, "ok", callback);
                return true;
            }
        });
        server.start();

        // ───────────── 5. Send 100 requests at the same time ─────────────
        int port = connector.getLocalPort(); // It was started on port 0, so look up the port actually assigned
        // 100 client-side threads (regular platform threads, unrelated to the server)
        ExecutorService clients = Executors.newFixedThreadPool(REQUESTS);
        try
        {
            List<Future<String>> responses = new ArrayList<>();
            for (int i = 0; i < REQUESTS; i++)
            {
                responses.add(clients.submit(() ->
                {
                    // Open a socket directly and send the HTTP request string as is
                    // (done this way because the JDK HttpClient can't be used due to the module setup; other jetty tests do it this way too)
                    try (Socket socket = new Socket("localhost", port))
                    {
                        socket.setSoTimeout(10_000); // Fails if there's no response within 10 seconds → detects a "stall"
                        OutputStream output = socket.getOutputStream();
                        output.write("""
                            GET / HTTP/1.1\r
                            Host: localhost\r
                            Connection: close\r
                            \r
                            """.getBytes(StandardCharsets.UTF_8));
                        output.flush();
                        // With Connection: close, the server closes the connection after responding → reading to the end gives the whole response
                        InputStream input = socket.getInputStream();
                        return IO.toString(input);
                    }
                }));
            }

            // (Check B) Whether all 100 responses came back as 200 + "ok" within 10 seconds
            // If even one stalls, get() times out → the test fails
            for (Future<String> response : responses)
            {
                String content = response.get(10, TimeUnit.SECONDS);
                assertThat(content, containsString(" 200 "));
                assertThat(content, containsString("ok"));
            }
        }
        finally
        {
            clients.shutdownNow();
        }

        // Print the measurements (result: peakActive=14 peakPoolThreads=16 maxThreads=16)
        System.err.printf("peakActive=%d peakPoolThreads=%d maxThreads=%d%n", peakActive.get(), peakPoolThreads.get(), MAX_THREADS);

        // (Check A result) Whether every request was handled on a virtual thread
        assertFalse(nonVirtualHandlerThread.get(), "a request was handled by a non-virtual thread");
        // (Check C) Whether 2 or more were handled at the same time = whether it really ran in parallel (if they ran one by one, the test is meaningless)
        assertThat(peakActive.get(), greaterThan(1));
        // (Check D) Whether the pool didn't create more than 16 even with virtual threads = whether the cap was respected
        assertThat(peakPoolThreads.get(), lessThanOrEqualTo(MAX_THREADS));
        // (Check E) Whether concurrent handling is 14 or less = the acceptor/selector take up 2 slots
        assertThat(peakActive.get(), lessThanOrEqualTo(MAX_THREADS - 2));
    }
}

The test completed successfully (it was just confirming with real server behavior what had already been verified in the previous tests), so I moved straight on to the documentation


Writing the Docs: Limiting Virtual Thread Creation with QueuedThreadPool


[[thread-pool-virtual-threads-queued-factory]]
==== Limiting Virtual Threads Creation with `QueuedThreadPool`

If you want to limit the number of virtual threads that are _created_, rather than the number of concurrent tasks, you can configure `QueuedThreadPool` with a virtual `ThreadFactory`:

[,java,indent=0]
----
include::code:example$src/main/java/org/eclipse/jetty/docs/programming/ArchitectureDocs.java[tags=queuedVirtualThreadFactory]
----

In this configuration, all the threads of `QueuedThreadPool` are virtual threads, and `QueuedThreadPool` behaves as it does with platform threads:

* At most `maxThreads` virtual threads are created; additional tasks wait in the `QueuedThreadPool` queue until a thread becomes available.
* Virtual threads are reused to run queued tasks.
* Idle virtual threads are evicted after `idleTimeout`, so that `QueuedThreadPool` shrinks back towards `minThreads`.

This differs from <<thread-pool-virtual-threads-virtual,`VirtualThreadPool`>>, which spawns a new virtual thread for each task and only limits the number of tasks that run concurrently.

[NOTE]
====
Configure the number of reserved threads explicitly to zero.

With the default configuration, `QueuedThreadPool` may start a reserved thread, which occupies one of the `maxThreads` slots while it waits for a task.
With virtual threads the cost of starting a thread is small, so it is typically better to use all the `maxThreads` slots to run tasks.
====

Like with platform threads, `QueuedThreadPool` leases threads to Jetty components, such as the acceptors and selectors of a `ServerConnector`, and leased threads occupy `maxThreads` slots.
Take them into account when choosing the value of `maxThreads`, as explained in <<thread-pool-configuration,this section>>.

Since the selector threads are virtual threads in this configuration, refer to <<thread-pool-virtual-threads-pinning,this section>> about virtual threads pinning.

The virtual threads created by a plain `Thread.ofVirtual().factory()` have no name; use `Thread.ofVirtual().name(prefix, start).factory()` to name them, so that they can be recognized in thread dumps and logs.

Summary of the Docs

To briefly summarize the content

it says that if you want to limit the number of virtual threads that get created, “you just put a virtual ThreadFactory into QueuedThreadPool.”

  • How it behaves : the threads of QueueThreadPool are virtual threads, and the pool behaves the same as when using platform threads
  • Difference from VirtualThreadPool : VirtualThreadPool creates a new virtual thread for each task and only limits the number of tasks running concurrently
  • Recommended setting : set reserved threads to 0 => it takes up one of the max thread slots (a setting originally designed with platform threads in mind), and since virtual threads are cheap to start, it’s better to use them all to run tasks
  • acceptor and selector : just like with platform threads, they take up max thread slots, so take that into account
  • pinning : refer to the pinning section
  • Thread names : virtual threads created with Thread.ofVirtual().factory() have no name. If you want them set up so they can be recognized in thread dumps or logs, use .name(prefix, start).

Opening the PR

jetty.project#16207 PR

I opened the PR with the content as is. Since what the issue asked for was documentation, I didn’t push the test code separately; I just kept it on a separate branch, shared only the test results, and only updated the docs. I said in the PR that I’d attach the test code too if they wanted, so I suspect they’ll probably ask for it during the review !


Edit page

Previous Post
Contributing to Hibernate ORM, Part 1: Analyzing the ClassCastException Caused by a Criteria Subquery Type Mismatch and Opening a PR
Next Post
Contributing to JUnit, Part 4: Writing the Release Note, Addressing the Maintainer's Review, and Getting Merged

Comments

Use your GitHub account to comment or react.