/*
* Created at 00:04 on 30/11/15
*/
package com.example.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.time.Duration;
import java.util.concurrent.*;
import java.util.function.Function;

/**
 * @author zzhao
 */
public final class AsyncUtil {

    private AsyncUtil() {
        throw new AssertionError("not for instantiation or inheritance");
    }

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1,
            new ThreadFactoryBuilder()
                    .setDaemon(true)
                    .setNameFormat("async-util-%d")
                    .build());

    private static TimeoutException timeout(Duration duration) {
        return new TimeoutException("timeout after: " + duration);
    }

    public static <T> CompletableFuture<T> timeoutAfter(CompletableFuture<T> original, Duration duration) {
        final CompletableFuture<T> future = new CompletableFuture<>();
        scheduler.schedule(() -> {
            future.completeExceptionally(timeout(duration));
            original.cancel(true);
        }, duration.toMillis(), TimeUnit.MILLISECONDS);
        return future;
    }

    public static <T> CompletableFuture<T> defaultAfter(CompletableFuture<T> original, Duration duration, T value) {
        final CompletableFuture<T> future = new CompletableFuture<>();
        scheduler.schedule(() -> {
            future.complete(value);
            original.cancel(true);
        }, duration.toMillis(), TimeUnit.MILLISECONDS);
        return future;
    }

    public static <T> CompletableFuture<T> withTimeout(CompletableFuture<T> original, Duration duration) {
        return original.applyToEither(timeoutAfter(original, duration), Function.<T>identity());
    }

    public static <T> CompletableFuture<T> withDefaultOnTimeout(
            CompletableFuture<T> original, Duration duration, T value) {
        return original.applyToEither(defaultAfter(original, duration, value), Function.<T>identity());
    }
}

@@ -61,72 +61,8 @@
 l;%0A%0A
-import com.google.common.util.concurrent.ThreadFactoryBuilder;%0A%0A
 impo
@@ -430,34 +430,81 @@
     
-new ThreadFactoryBuilder()
+r -%3E %7B%0A                final Thread thread = new Thread(r, %22async-util%22);
 %0A   
@@ -512,28 +512,30 @@
             
-    
+thread
 .setDaemon(t
@@ -538,18 +538,18 @@
 on(true)
+;
 %0A
- 
         
@@ -560,71 +560,36 @@
     
-   .setNameFormat(%22async-util-%25d%22)%0A                    .build()
+return thread;%0A            %7D
 );%0A%0A

remove guava dependency from async util