Last active
April 25, 2018 22:10
-
-
Save gabfssilva/600d5991cfe93d483357f4a7ef2202e3 to your computer and use it in GitHub Desktop.
Future to CompletableFeature converter
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.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.concurrent.*; | |
import java.util.stream.Collectors; | |
class FutureWrapper<T> { | |
Future<T> future; | |
CompletableFuture<T> completableFuture; | |
FutureWrapper(Future<T> future, CompletableFuture<T> completableFuture) { | |
this.future = future; | |
this.completableFuture = completableFuture; | |
} | |
void complete() { | |
try { | |
completableFuture.complete(future.get()); | |
} catch (Exception e) { | |
completableFuture.completeExceptionally(e); | |
} | |
} | |
void cancel() { | |
completableFuture.cancel(true); | |
} | |
} | |
public class FutureUtils { | |
private static List<FutureWrapper<?>> futureStream = Collections.synchronizedList(new ArrayList<>()); | |
private static final ScheduledExecutorService SERVICE = Executors.newSingleThreadScheduledExecutor(); | |
static { | |
SERVICE.scheduleWithFixedDelay(FutureUtils::check, 0, 1, TimeUnit.MILLISECONDS); | |
} | |
private synchronized static void check() { | |
final List<FutureWrapper<?>> finishedStream = | |
futureStream | |
.stream() | |
.filter(wrapper -> wrapper.future.isDone()) | |
.collect(Collectors.toList()); | |
finishedStream.forEach(FutureWrapper::complete); | |
futureStream = futureStream.stream().filter(s -> !finishedStream.contains(s)).collect(Collectors.toList()); | |
final List<FutureWrapper<?>> cancelledStream = | |
futureStream | |
.stream() | |
.filter(wrapper -> wrapper.future.isCancelled()) | |
.collect(Collectors.toList()); | |
cancelledStream.forEach(FutureWrapper::cancel); | |
futureStream = futureStream.stream().filter(s -> !cancelledStream.contains(s)).collect(Collectors.toList()); | |
} | |
public static <T> CompletableFuture<T> asCompletableFuture(Future<T> f) { | |
CompletableFuture<T> c = new CompletableFuture<T>(); | |
futureStream.add(new FutureWrapper<>(f, c)); | |
return c; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: