Created
February 1, 2024 07:58
-
-
Save mskoroglu/8ade232725eadf7ae5737c598774e0b1 to your computer and use it in GitHub Desktop.
Virtual Threads with async/await in Java
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.mustafakoroglu.gist.virtualfuture; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
import java.util.function.Supplier; | |
import java.util.stream.StreamSupport; | |
public final class VirtualFuture<T> { | |
private static final ExecutorService EXECUTOR = Executors.newThreadPerTaskExecutor( | |
Thread.ofVirtual().name("vfuture-", 0).factory() | |
); | |
private final Future<T> future; | |
private VirtualFuture(final Future<T> future) { | |
this.future = future; | |
} | |
public static <T> VirtualFuture<T> async(final Supplier<T> supplier) { | |
return new VirtualFuture<>(EXECUTOR.submit(supplier::get)); | |
} | |
public static VirtualFuture<Void> async(final Runnable runnable) { | |
return new VirtualFuture<>((Future<Void>) EXECUTOR.submit(runnable)); | |
} | |
public static <T> T await(final VirtualFuture<T> virtualFuture) { | |
try { | |
return virtualFuture.future.get(); | |
} catch (final InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
throw new UncheckedExecutionException(e); | |
} catch (final ExecutionException e) { | |
throw new UncheckedExecutionException(e); | |
} | |
} | |
@SafeVarargs | |
public static <T> List<T> awaitAll(final VirtualFuture<T>... fs) { | |
return Arrays.stream(fs).map(VirtualFuture::await).toList(); | |
} | |
public static <T> List<T> awaitAll(final Iterable<VirtualFuture<T>> fs) { | |
return StreamSupport.stream(fs.spliterator(), false).map(VirtualFuture::await).toList(); | |
} | |
private static final class UncheckedExecutionException extends RuntimeException { | |
public UncheckedExecutionException(final Throwable cause) { | |
super(cause); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment