Created
September 12, 2024 10:16
-
-
Save pivovarit/c3ca1531ca1fe4adf75aa75132493065 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pivovarit.demo; | |
import com.pivovarit.collectors.ParallelCollectors; | |
import java.io.IOException; | |
import java.net.URI; | |
import java.net.http.HttpClient; | |
import java.net.http.HttpRequest; | |
import java.net.http.HttpResponse; | |
import java.util.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.function.Supplier; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
/** | |
* @author Grzegorz Piwowarek | |
* @twitter @pivovarit | |
* @github pivovarit | |
*/ | |
class VirtualThreadsInAction { | |
public static void main(String[] args) { | |
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) { | |
List<Integer> result = timed(() -> Stream.iterate(0, i -> i + 1) | |
.limit(1000) | |
.collect(ParallelCollectors.parallel(i -> process(i), Collectors.toList(), ex)) | |
.join()); | |
} | |
} | |
private static <T> T timed(Supplier<T> action) { | |
long before = System.currentTimeMillis(); | |
T result = action.get(); | |
long after = System.currentTimeMillis(); | |
System.out.println("took " + (after - before) + "ms"); | |
return result; | |
} | |
private static <T> T process(T input) { | |
System.out.println("processing " + input + " on " + Thread.currentThread().getName()); | |
try { | |
synchronized (new Object()) { | |
Thread.sleep(2000); | |
} | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
return input; | |
} | |
public static void perfTest(String[] args) throws InterruptedException { | |
ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor(); | |
for (int i = 0; i < 5000; i++) { | |
CompletableFuture.runAsync(() -> { | |
try { | |
var before = System.currentTimeMillis(); | |
String result = HttpClient.newHttpClient() | |
.send(HttpRequest.newBuilder() | |
.GET() | |
.uri(URI.create("http://localhost:8080/api/uuid")) | |
.build(), HttpResponse.BodyHandlers.ofString()) | |
.body(); | |
var after = System.currentTimeMillis(); | |
System.out.printf("result = %s in %dms%n", result, after - before); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
}, ex); | |
} | |
Thread.sleep(100000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment