Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. public class FutureOps {
  2.     public static <T> CompletableFuture<T> makeCompletableFuture(Future<T> future) {
  3.         if (future.isDone())
  4.             return transformDoneFuture(future);
  5.         return CompletableFuture.supplyAsync(() -> {
  6.             try {
  7.                 if (!future.isDone())
  8.                     awaitFutureIsDoneInForkJoinPool(future);
  9.                 return future.get();
  10.             } catch (ExecutionException e) {
  11.                 throw new RuntimeException(e);
  12.             } catch (InterruptedException e) {
  13.                 // Normally, this should never happen inside ForkJoinPool
  14.                 Thread.currentThread().interrupt();
  15.                 // Add the following statement if the future doesn't have side effects
  16.                 // future.cancel(true);
  17.                 throw new RuntimeException(e);
  18.             }
  19.         });
  20.     }
  21.  
  22.     private static <T> CompletableFuture<T> transformDoneFuture(Future<T> future) {
  23.         CompletableFuture<T> cf = new CompletableFuture<>();
  24.         T result;
  25.         try {
  26.             result = future.get();
  27.         } catch (Throwable ex) {
  28.             cf.completeExceptionally(ex);
  29.             return cf;
  30.         }
  31.         cf.complete(result);
  32.         return cf;
  33.     }
  34.  
  35.     private static void awaitFutureIsDoneInForkJoinPool(Future<?> future)
  36.             throws InterruptedException {
  37.         ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() {
  38.             @Override public boolean block() throws InterruptedException {
  39.                 try {
  40.                     future.get();
  41.                 } catch (ExecutionException e) {
  42.                     throw new RuntimeException(e);
  43.                 }
  44.                 return true;
  45.             }
  46.             @Override public boolean isReleasable() {
  47.                 return future.isDone();
  48.             }
  49.         });
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement