package com.github.phantomthief.concurrent;

import static org.slf4j.LoggerFactory.getLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;

import com.github.phantomthief.util.ThrowableRunnable;
import com.google.common.util.concurrent.ForwardingListenableFuture;
import com.google.common.util.concurrent.ListenableFuture;

/**
 * @author w.vela
 * Created on 16/5/31.
 */
public class TimeoutListenableFuture<V> extends ForwardingListenableFuture<V> {

    private static final Logger logger = getLogger(TimeoutListenableFuture.class);

    private final ListenableFuture<V> delegate;
    private final List<ThrowableRunnable<Exception>> timeoutListeners = new ArrayList<>();

    public TimeoutListenableFuture(ListenableFuture<V> delegate) {
        this.delegate = delegate;
    }

    @Override
    protected ListenableFuture<V> delegate() {
        return delegate;
    }

    public TimeoutListenableFuture<V> addTimeoutListener(ThrowableRunnable<Exception> consumer) {
        timeoutListeners.add(consumer);
        return this;
    }

    @Override
    public V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
        try {
            return delegate().get(timeout, unit);
        } catch (TimeoutException e) {
            for (ThrowableRunnable<Exception> timeoutListener : timeoutListeners) {
                try {
                    timeoutListener.run();
                } catch (Exception e1) {
                    logger.error("", e1);
                }
            }
            throw e;
        }
    }
}

@@ -38,16 +38,81 @@
 rrent;%0A%0A
+import static com.google.common.base.Preconditions.checkNotNull;%0A
 import s
@@ -348,26 +348,115 @@
 ort 
-org.slf4j.Logger;%0A
+javax.annotation.Nonnull;%0A%0Aimport org.slf4j.Logger;%0A%0Aimport com.github.phantomthief.util.ThrowableConsumer;
 %0Aimp
@@ -926,33 +926,51 @@
 st%3CThrowable
-Runnable%3C
+Consumer%3CTimeoutException, 
 Exception%3E%3E 
@@ -1246,16 +1246,28 @@
 uture%3CV%3E
+%0A           
  addTime
@@ -1278,16 +1278,25 @@
 istener(
+@Nonnull 
 Throwabl
@@ -1316,22 +1316,254 @@
 eption%3E 
-consum
+listener) %7B%0A        checkNotNull(listener);%0A        return addTimeoutListener(e -%3E listener.run());%0A    %7D%0A%0A    public TimeoutListenableFuture%3CV%3E%0A            addTimeoutListener(@Nonnull ThrowableConsumer%3CTimeoutException, Exception%3E listen
 er) %7B%0A  
@@ -1594,16 +1594,30 @@
 dd(c
-onsum
+heckNotNull(listen
 er)
+)
 ;%0A  
@@ -1915,36 +1915,47 @@
 able
-Runnable%3CException%3E timeoutL
+Consumer%3CTimeoutException, Exception%3E l
 iste
@@ -2026,28 +2026,25 @@
     
-timeoutListener.run(
+listener.accept(e
 );%0A 

add an exception consumer version listener for TimeoutListenableFuture.