Created
July 29, 2017 08:50
-
-
Save chenqiyue/ed70122847cdf432a9559eb51b4c638a to your computer and use it in GitHub Desktop.
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.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.Executor; | |
import java.util.concurrent.Future; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
/** | |
* @author cqy | |
* @since 2017/7/29. | |
*/ | |
public abstract class CompletableFutureUtil { | |
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) { | |
CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); | |
return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.<T>toList())); | |
} | |
public static <T> CompletableFuture<Stream<T>> sequence(Stream<CompletableFuture<T>> futures) { | |
CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)); | |
return allDoneFuture.thenApply(v -> futures.map(CompletableFuture::join)); | |
} | |
public static <T> CompletableFuture<T> toCompletable(Future<T> future, Executor executor) { | |
if (future instanceof CompletableFuture) { | |
return (CompletableFuture<T>) future; | |
} | |
return CompletableFuture.supplyAsync(() -> { | |
try { | |
return future.get(); | |
} catch (InterruptedException | ExecutionException e) { | |
throw new RuntimeException(e); | |
} | |
}, executor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment