Created
May 12, 2022 13:13
-
-
Save Sanne/42d9a79be578306ffd64e11af252dad6 to your computer and use it in GitHub Desktop.
Exploring scheduling strategy of async CompletableFuture(s)
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
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