Java 가상쓰레드 속도 비교

목표

일반 thread 와 가상 thread 속도 비교하기(IO작업)

일반 thread 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class PlatformThreadTest {
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
.uri(new URI("http://localhost:4000/"))
.build();

int totalRequests = 100000;
int batchSize = 100;
int numBatches = totalRequests / batchSize;

Instant start = Instant.now();

for (int batch = 0; batch < numBatches; batch++) {
var executor = Executors.newFixedThreadPool(batchSize);
CompletableFuture<?>[] futures = new CompletableFuture<?>[batchSize];

for (int i = 0; i < batchSize; i++) {
futures[i] = CompletableFuture.runAsync(() -> {
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// System.out.println("Response code: " + response.statusCode());
} catch (Exception e) {
e.printStackTrace();
}
}, executor);
}

CompletableFuture.allOf(futures).join();
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
}

Instant end = Instant.now();
System.out.println("Time taken with platform threads: " + Duration.between(start, end).toMillis() + " ms");
}
}
자세히 보기