get Generic Future With Delay - Java java.util.concurrent

Java examples for java.util.concurrent:Future

Description

get Generic Future With Delay

Demo Code


//package com.java2s;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Main {
    public static <V> Future<V> getGenericFutureWithDelay(
            final V returnValue, final long delay) {
        return new Future<V>() {
            boolean cancelled = false;
            boolean done = false;
            long timerStarted = -1;

            @Override/*ww  w  . jav  a2  s.  co m*/
            public boolean cancel(boolean mayInterruptIfRunning) {
                cancelled = true;
                return true;
            }

            @Override
            public V get() throws InterruptedException, ExecutionException {
                if (timerStarted < 0) {
                    timerStarted = System.currentTimeMillis();
                }

                long elapsed = (System.currentTimeMillis() - timerStarted);

                if (elapsed < delay) {
                    Thread.sleep(delay);
                }
                done = true;
                return returnValue;
            }

            @Override
            public V get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException,
                    TimeoutException {

                if (timerStarted < 0) {
                    timerStarted = System.currentTimeMillis();
                }

                long elapsed = (System.currentTimeMillis() - timerStarted);

                if (elapsed >= delay) {
                    done = true;
                    return returnValue;
                } else {
                    Thread.sleep(delay);
                    throw new TimeoutException("Not completed yet");
                }
            }

            @Override
            public boolean isCancelled() {
                return cancelled;
            }

            @Override
            public boolean isDone() {
                return done;
            }
        };
    }
}

Related Tutorials