Skip to content

Instantly share code, notes, and snippets.

@kamzrk
Last active February 28, 2025 06:35
Show Gist options
  • Save kamzrk/2b73134bf82cb2a0e9f765e355903c14 to your computer and use it in GitHub Desktop.
Save kamzrk/2b73134bf82cb2a0e9f765e355903c14 to your computer and use it in GitHub Desktop.
Virtual threads and ThreadLocal
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
@Log4j2
class TLTest {
@Test
@SneakyThrows
void given_when_should() {
int availableProcessors = Runtime.getRuntime()
.availableProcessors();
System.out.println("Detected CPU with " + availableProcessors + " logical threads.");
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(1, 50)
.mapToObj(this::createTask)
.forEach(task -> {
executor.submit(task);
});
}
}
private Runnable createTask(int i) {
return () -> {
System.out.println("Start[" + i + "]: " + Thread.currentThread() + ": " + threadLocal.get());
threadLocal.set("Task" + i);
if (i % 2 == 0) {
try {
// Simulate I/O blocking (e.g., reading a file)
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("End[" + i + "]: " + Thread.currentThread() + ": " + threadLocal.get());
};
}
private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment