Java examples for java.util.concurrent:Future
get Generic concurrent Future
//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> getGenericFuture(final V returnValue) { return getGenericFutureWithDelay(returnValue, 0); }// ww w.j a va2 s. c o m 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 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; } }; } }