Skip to content
Being BE
Go back

Jetty 오픈소스 기여 2편: 실제 서버 테스트와 문서 작성, 그리고 PR 올리기

—viewsEdit page
목차

이슈에 중간결과를 공유했지만 피드백이 안와서 어차피 help-wanted라벨이 붙어있었으니 그냥 PR을 올리기로 했다!

우선 PR을 올리기전 나머지 작업을 완료하여야했고 이전에 관련테스트는 모두 끝냈지만 실제 서버테스트와 문서화는 하지 않았기에 해당 사항들을 마쳐야했다

GitHub Repository
Eclipse Jetty
jetty/jetty.project

자바 기반 웹 서버이자 서블릿 컨테이너

GitHub에서 보기
Eclipse Jetty GitHub 저장소 미리보기
Jetty 오픈소스 기여 시리즈

1편 · 가상 스레드 생성 수 제한 이슈 탐색과 검증

2편 · 실제 서버 테스트와 문서 작성, 그리고 PR 올리기


실제 서버에서 동작을 확인하는 테스트 추가

// JDK 20 이하에는 가상 스레드가 없으니 테스트를 건너뜀
@DisabledForJreRange(max = JRE.JAVA_20)
public class QueuedThreadPoolVirtualThreadServerTest
{
    // 스레드 풀이 만들 수 있는 스레드의 최대 개수 
    private static final int MAX_THREADS = 16;
    // 동시에 보낼 HTTP 요청 수. 상한(16)보다 훨씬 많아야 "상한에 막히는지"를 볼 수 있음
    private static final int REQUESTS = 100;

    private Server server;

    // jetty는 Java 17 기준으로 컴파일돼서 이 API를 직접 쓸 수 없음 → 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. 스레드 풀 준비 ─────────────
        QueuedThreadPool qtp = new QueuedThreadPool(MAX_THREADS, 1, 60_000, 0, null, null, virtualThreadFactory());

        // ───────────── 2. 서버 준비 ─────────────
        server = new Server(qtp);
        // acceptor 1개(새 연결 받기) + selector 1개(어느 연결에 데이터가 왔는지 감시)
        // 이 둘도 qtp의 스레드를 하나씩 계속 점유함 → 요청 처리에 쓸 수 있는 건 16 - 2 = 14개
        ServerConnector connector = new ServerConnector(server, 1, 1);
        server.addConnector(connector);

        // ───────────── 3. 측정용 변수 ─────────────
        // 여러 스레드가 동시에 건드리니까 Atomic 사용
        AtomicInteger active = new AtomicInteger();            // 지금 Handler 안에서 처리 중인 요청 수
        AtomicInteger peakActive = new AtomicInteger();        // 그 값의 최댓값 (동시 처리 최대치)
        AtomicInteger peakPoolThreads = new AtomicInteger();   // 풀이 만든 스레드 수의 최댓값
        AtomicBoolean nonVirtualHandlerThread = new AtomicBoolean(); // 가상 스레드가 아닌 곳에서 처리된 적이 있는지

        // ───────────── 4. 요청 처리 Handler ─────────────
        // Servlet 대신 Jetty 12 core API. 요청 하나가 들어올 때마다 handle()이 풀의 스레드에서 실행됨
        server.setHandler(new Handler.Abstract()
        {
            @Override
            public boolean handle(Request request, Response response, Callback callback) throws Exception
            {
                // (검사 A) 지금 이 코드를 돌리는 스레드가 가상 스레드인지
                if (!VirtualThreads.isVirtualThread())
                    nonVirtualHandlerThread.set(true);

                // 들어왔으니 active +1, 그 값이 지금까지 최대면 peakActive 갱신
                peakActive.accumulateAndGet(active.incrementAndGet(), Math::max);
                // 이 순간 풀이 만들어 둔 스레드 수를 기록 (최댓값 유지)
                peakPoolThreads.accumulateAndGet(qtp.getThreads(), Math::max);
                try
                {
                    // 일부러 50ms 블로킹 (DB 조회 같은 느린 작업 흉내)
                    // 요청이 빨리 끝나 버리면 동시에 겹치지 않아서 상한을 시험할 수 없음
                    Thread.sleep(50);
                }
                finally
                {
                    // 처리 끝 → active -1
                    active.decrementAndGet();
                }
                // 응답: 200 + 본문 "ok"
                response.setStatus(200);
                Content.Sink.write(response, true, "ok", callback);
                return true;
            }
        });
        server.start();

        // ───────────── 5. 요청 100개를 동시에 보내기 ─────────────
        int port = connector.getLocalPort(); // 포트 0으로 띄웠으니 실제 할당된 포트를 조회
        // 클라이언트 쪽 스레드 100개 (일반 플랫폼 스레드, 서버와 무관)
        ExecutorService clients = Executors.newFixedThreadPool(REQUESTS);
        try
        {
            List<Future<String>> responses = new ArrayList<>();
            for (int i = 0; i < REQUESTS; i++)
            {
                responses.add(clients.submit(() ->
                {
                    // 소켓을 직접 열어서 HTTP 요청 문자열을 그대로 보냄
                    // (모듈 설정 때문에 JDK HttpClient를 못 써서 이 방식, 다른 jetty 테스트도 이렇게 함)
                    try (Socket socket = new Socket("localhost", port))
                    {
                        socket.setSoTimeout(10_000); // 10초 안에 응답이 없으면 실패 → "멈춤" 감지
                        OutputStream output = socket.getOutputStream();
                        output.write("""
                            GET / HTTP/1.1\r
                            Host: localhost\r
                            Connection: close\r
                            \r
                            """.getBytes(StandardCharsets.UTF_8));
                        output.flush();
                        // Connection: close라서 서버가 응답 후 연결을 닫음 → 끝까지 읽으면 응답 전체
                        InputStream input = socket.getInputStream();
                        return IO.toString(input);
                    }
                }));
            }

            // (검사 B) 100개 응답이 모두 10초 안에 200 + "ok"로 왔는지
            // 하나라도 멈추면 get()에서 타임아웃 → 테스트 실패
            for (Future<String> response : responses)
            {
                String content = response.get(10, TimeUnit.SECONDS);
                assertThat(content, containsString(" 200 "));
                assertThat(content, containsString("ok"));
            }
        }
        finally
        {
            clients.shutdownNow();
        }

        // 측정값 출력 (결과: peakActive=14 peakPoolThreads=16 maxThreads=16)
        System.err.printf("peakActive=%d peakPoolThreads=%d maxThreads=%d%n", peakActive.get(), peakPoolThreads.get(), MAX_THREADS);

        // (검사 A 결과) 모든 요청이 가상 스레드에서 처리됐는지
        assertFalse(nonVirtualHandlerThread.get(), "a request was handled by a non-virtual thread");
        // (검사 C) 동시에 2개 이상 처리됐는지 = 정말 병렬로 돌았는지 (하나씩 돌았으면 의미 없는 테스트)
        assertThat(peakActive.get(), greaterThan(1));
        // (검사 D) 가상 스레드인데도 풀이 16개를 넘겨 만들지 않았는지 = 상한이 지켜졌는지
        assertThat(peakPoolThreads.get(), lessThanOrEqualTo(MAX_THREADS));
        // (검사 E) 동시 처리 수가 14 이하인지 = acceptor/selector가 슬롯 2개를 먹는다는 것
        assertThat(peakActive.get(), lessThanOrEqualTo(MAX_THREADS - 2));
    }
}

테스트는 성공적으로 완료가 되어서(이미 이전 테스트들에서 검증이된 바를 실제 서버동작으로 확인한것뿐) 바로 문서 작업으로 넘어갔다


문서 작성: 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.

문서 내용 요약

내용을 간략히 요약하여 보자면

만들어지는 가상 스레드 수를 제한하고 싶다면 “QueuedThreadPool에 가상 ThreadFactory를 넣으면 된다.” 라는 이야기이며

  • 동작 설명 : QueueThreadPool의 스레드는 가상스레드이며 풀은 플랫폼 스레드 사용시와 동일하게 동작
  • VirtualThreadPool과의 차이 : VirtualThreadPool은 작업마다 새로운 가상스레드 동시 실행되는 작업수만 제한
  • 추천 설정 : 예약스레드는 0으로 설정하라 => 최대스레드 갯수중 하나를 차지하니(원래는 플랫폼 스레드를 염두에둔 설정) 가상스레드는 시작 비용이 작으니 모두 작업 실행에 쓰는게 낫다
  • acceptor와 selector : 플랫폼 스레드와 마찬가지로 최대 스레드갯수 슬롯을 차지하니 이걸 고려하라
  • pinning : pinning 참고하라
  • 스레드이름 : Thread.ofVirtual().factory()로 만든 가상 스레드는 이름이 없다 스레드 덤프나 로그에서 알아볼 수 있게 설정을 원한다면 .name(prefix, start)를 써라.

PR 올리기

jetty.project#16207 PR

내용을 그대로 담아서 PR을 올렸다 이슈에서 요청사항이 문서작성이였기에 별도로 테스트 코드를 올리진 않고 별도 브랜치만 분리해서 보관하고 테스트결과만 공유하고 문서 업데이트만 하였다 PR에 원할시 테스트코드도 첨부하겠다고 밝혔으니 아마도 리뷰과정에서 요청을 하지 않을까 싶다 !


Edit page

Previous Post
Hibernate ORM 오픈소스 기여 1편: Criteria 서브쿼리 타입 불일치로 터지는 ClassCastException 분석하고 PR 올리기
Next Post
JUnit 오픈소스 기여 4편: 릴리스 노트 작성과 메인테이너 리뷰 반영, 그리고 머지

댓글

GitHub 계정으로 의견을 남기거나 글에 반응할 수 있습니다.