Skip to content

Instantly share code, notes, and snippets.

@Sanne
Created May 12, 2022 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sanne/42d9a79be578306ffd64e11af252dad6 to your computer and use it in GitHub Desktop.
Save Sanne/42d9a79be578306ffd64e11af252dad6 to your computer and use it in GitHub Desktop.
Exploring scheduling strategy of async CompletableFuture(s)
import java.util.concurrent.CompletableFuture;
public class OtherApp {
private static final boolean wait = false;
public static void main(String[] args) {
VeryParallelExecutor executor = new VeryParallelExecutor( 4 );
OneOffDelegatingExecutor taskControl = new OneOffDelegatingExecutor( executor );
CompletableFuture<Integer> supplier = CompletableFuture.supplyAsync(
OtherApp::asyncGenerateInteger,
taskControl
);
sleep2seconds();
CompletableFuture<Void> future = supplier
.thenApply( OtherApp::incrementInput )
.thenAccept( OtherApp::printOutput );
taskControl.runHeldTasks();
future.join();
executor.shutdownAndWait();
}
private static Integer asyncGenerateInteger() {
if (wait) sleep2seconds();
System.out.println( "asyncGenerateInteger: " + Thread.currentThread().getName() );
return 1;
}
private static void sleep2seconds() {
try {
Thread.sleep( 2000 );
}
catch (InterruptedException ignored) {
ignored.printStackTrace();
}
}
private static Integer incrementInput(Integer i) {
System.out.println( "incrementInput: " + Thread.currentThread().getName() );
return i + 1;
}
private static void printOutput(Integer i) {
System.out.println( "printOutput: " + Thread.currentThread().getName() );
System.out.println( "result is: " + i );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment