Skip to content

Instantly share code, notes, and snippets.

@liufuyang
Created November 21, 2019 00:16
Show Gist options
  • Save liufuyang/996bea6eb2fb3b27aeca7fb2fcc4c30d to your computer and use it in GitHub Desktop.
Save liufuyang/996bea6eb2fb3b27aeca7fb2fcc4c30d to your computer and use it in GitHub Desktop.
CompletableFutures newWorkStealingPool test
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class G1Test {
Logger logger = LoggerFactory.getLogger(G1Test.class);
// ExecutorService e1 = Executors.newFixedThreadPool(2);
ExecutorService e1 = Executors.newWorkStealingPool(2);
@Test
public void test() {
// Gather CompletableFutures to wait for them at the end
List<CompletableFuture> futures = new ArrayList<>();
// First steps
for (int i = 0; i < 5; i++) {
int finalI = i;
CompletableFuture<Void> fut = CompletableFuture.supplyAsync(() -> {
logger.info("Start step a - " + finalI);
//simulateLongProcessing();// just waits for 1 s
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("End step a - " + finalI);
return "step1 output - " + finalI;
}, e1)
.orTimeout(5000, TimeUnit.MILLISECONDS)
.exceptionally(t -> "exp 1 output " + finalI)
.thenComposeAsync(s -> {
List<CompletableFuture> subFutures = new ArrayList<>();
// Second step : Launch several sub-tasks based on the result of the first step
for (int j = 0; j < 5; j++) {
final int finalJ = j;
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
logger.info("Start - step b : " + s + " | " + finalJ);
//simulateLongProcessing();
logger.info("End - step b : " + s + " | " + finalJ);
return "step2 output - " + s + " | " + finalJ;
}, e1);
subFutures.add(f);
}
return CompletableFuture.allOf(subFutures.toArray(new CompletableFuture[0]));
}, e1);
futures.add(fut);
}
// Wait for the completion
for (CompletableFuture future : futures) {
future.join();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment