Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask FutureTask.

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:net.dryuf.concurrent.benchmark.SinglePostListenerBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)//w  w w  . j a  v a2 s . c  o  m
@Measurement(iterations = 1, batchSize = 1)
@Fork(warmups = 1, value = 1)
public void benchmarkJdk() throws Exception {
    for (long i = 0; i < COUNT; ++i) {
        FutureTask<Integer> future = new FutureTask<Integer>(() -> {
            return 0;
        });
        future.run();
    }
}

From source file:net.dryuf.concurrent.benchmark.MixedListenerBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)//from ww  w .  j ava 2  s.  c o m
@Measurement(iterations = 2, batchSize = 1)
@Fork(warmups = 1, value = 1)
public void benchmarkJdk() throws Exception {
    for (long i = 0; i < COUNT; ++i) {
        FutureTask<Integer> future = new FutureTask<Integer>(() -> {
            return 0;
        });
        future.run();
        future.get();
    }
}

From source file:net.dryuf.concurrent.benchmark.DoublePreListenerBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)//  www . ja  va 2  s  .  c  om
@Measurement(iterations = 1, batchSize = 1)
@Fork(warmups = 1, value = 1)
public void benchmarkJdk() throws Exception {
    for (long i = 0; i < COUNT; ++i) {
        FutureTask<Integer> future = new FutureTask<Integer>(() -> {
            return 0;
        });
        future.run();
        future.get();
    }
}

From source file:org.t2framework.commons.util.LazyLoadingReference.java

 public T get() throws IllegalStateException {
   while (true) {
      WeakReference<Future<T>> ref = reference.get();
      boolean valid = true;
      if (ref == null) {
         FutureTask<T> f = new FutureTask<T>(new Callable<T>() {
            @Override//from w w  w . j a  v a  2s  .  com
            public T call() throws Exception {
               return factory.create();
            }
         });
         ref = new WeakReference<Future<T>>(f);
         if (valid = reference.compareAndSet(null, ref)) {
            f.run();
         }
      }
      if (valid) {
         try {
            Future<T> f = ref.get();
            if (f != null) {
               return f.get();
            } else {
               reference.compareAndSet(ref, null);
            }
         } catch (CancellationException e) {
            reference.compareAndSet(ref, null);
         } catch (ExecutionException e) {
            throw new IllegalStateException(e.getCause());
         } catch (Exception e) {
            throw new IllegalStateException(e);
         }
      }
   }
}

From source file:org.eclipse.jubula.rc.javafx.driver.EventThreadQueuerJavaFXImpl.java

/**
 * Executes the given Callable on the JavaFX-Thread and waits for the
 * termination/*  w  w w . ja v  a  2  s. c  o  m*/
 *
 * @param name
 *            a name to identifier which Callable is being executed
 * @param <V>
 *            return value type
 * @param call
 *            the Callable
 * @return
 * @return the return value of the given Callable
 * @throws ExecutionException
 * @throws InterruptedException
 */
public static <V> V invokeAndWait(String name, Callable<V> call) {

    if (Platform.isFxApplicationThread()) {
        try {
            return call.call();
        } catch (Exception e) {
            // the run() method from IRunnable has thrown an exception
            // -> log on info
            // -> throw a StepExecutionException
            Throwable thrown = e.getCause();
            if (thrown instanceof StepExecutionException) {
                if (log.isInfoEnabled()) {
                    log.info(e);
                }
                throw (StepExecutionException) thrown;
            }

            // any other (unchecked) Exception from IRunnable.run()
            log.error("exception thrown by '" + name //$NON-NLS-1$
                    + "':", thrown); //$NON-NLS-1$
            throw new StepExecutionException(thrown);
        }
    }
    try {
        FutureTask<V> task = new FutureTask<>(call);
        Platform.runLater(task);
        return task.get();

    } catch (InterruptedException ie) {
        // this (the waiting) thread was interrupted -> error
        log.error(ie);
        throw new StepExecutionException(ie);
    } catch (ExecutionException ee) {
        // the run() method from IRunnable has thrown an exception
        // -> log on info
        // -> throw a StepExecutionException
        Throwable thrown = ee.getCause();
        if (thrown instanceof StepExecutionException) {
            if (log.isInfoEnabled()) {
                log.info(ee);
            }
            throw (StepExecutionException) thrown;
        }

        // any other (unchecked) Exception from IRunnable.run()
        log.error("exception thrown by '" + name //$NON-NLS-1$
                + "':", thrown); //$NON-NLS-1$
        throw new StepExecutionException(thrown);
    }
}

From source file:com.loopj.android.http.sample.AsyncBackgroundThreadSample.java

@Override
public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers,
        HttpEntity entity, final ResponseHandlerInterface responseHandler) {

    final Activity ctx = this;
    FutureTask<RequestHandle> future = new FutureTask<>(new Callable<RequestHandle>() {
        public RequestHandle call() {
            Log.d(LOG_TAG, "Executing GET request on background thread");
            return client.get(ctx, URL, headers, null, responseHandler);
        }//from   w w  w. ja  v  a 2  s .  co  m
    });

    executor.execute(future);

    RequestHandle handle = null;
    try {
        handle = future.get(5, TimeUnit.SECONDS);
        Log.d(LOG_TAG, "Background thread for GET request has finished");
    } catch (Exception e) {
        Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    return handle;
}

From source file:org.commonjava.indy.ftest.core.fixture.ThreadDumper.java

public static TestRule timeoutRule(int timeout, TimeUnit units) {
    return (base, description) -> new Statement() {
        public void evaluate() throws Throwable {
            System.out.printf("Setting up timeout: %d %s to wrap: %s\n", timeout, units, base);
            AtomicReference<Throwable> error = new AtomicReference<>();
            CountDownLatch latch = new CountDownLatch(1);
            FutureTask<Void> task = new FutureTask<>(() -> {
                try {
                    latch.countDown();//from  w  w  w.  j av a 2  s.com
                    base.evaluate();
                } catch (Throwable t) {
                    error.set(t);
                }

                return null;
            });

            ThreadGroup tg = new ThreadGroup("Test Timeout Group");
            Thread t = new Thread(tg, task, "Test Timeout Thread");
            t.setDaemon(true);
            t.start();

            try {
                System.out.println("Waiting for test to start.");
                latch.await();
            } catch (InterruptedException e) {
                error.set(e);
            }

            if (error.get() == null) {
                try {
                    System.out.println("Waiting for test to complete (or timeout)");
                    task.get(timeout, units);
                } catch (InterruptedException e) {
                    error.set(e);
                } catch (ExecutionException e) {
                    error.set(e.getCause());
                } catch (TimeoutException e) {
                    System.out.printf("Test timeout %d %s expired!\n", timeout, units.name());
                    dumpThreads();
                    StackTraceElement[] stackTrace = t.getStackTrace();
                    Exception currThreadException = new TestTimedOutException(timeout, units);
                    if (stackTrace != null) {
                        currThreadException.setStackTrace(stackTrace);
                        t.interrupt();
                    }

                    throw currThreadException;
                }
            }

            Throwable throwable = error.get();
            if (throwable != null) {
                throw throwable;
            }
        }
    };
}

From source file:org.devtcg.five.meta.LastfmMetaTask.java

public LastfmMetaTask(MetaProvider provider, long id) {
    mProvider = provider;
    mTask = new FutureTask<Object>(this);
    mId = id;
}

From source file:org.apache.stratos.load.balancer.mediators.ResponseInterceptor.java

public boolean mediate(MessageContext messageContext) {
    try {/*from  ww w  .  ja va  2s .c o m*/
        if (log.isDebugEnabled()) {
            log.debug("Response interceptor mediation started");
        }
        String clusterId = (String) messageContext.getProperty(Constants.CLUSTER_ID);
        if (StringUtils.isNotBlank(clusterId)) {
            FutureTask<Object> task = new FutureTask<Object>(new InFlightRequestDecrementCallable(clusterId));
            LoadBalancerStatisticsExecutor.getInstance().getService().submit(task);
        } else {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Could not decrement in-flight request count : cluster id not found in message context");
            }
        }

    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Could not decrement in-flight request count", e);
        }
    }
    return true;
}

From source file:Main.java

/**
 * Invoke the specified <code>Callable</code> on the AWT event dispatching thread now and return
 * the result.<br>/*  w ww. j  a v a  2 s.c om*/
 * The returned result can be <code>null</code> when a {@link Throwable} exception happen.<br>
 * Use this method carefully as it may lead to dead lock.
 * 
 * @throws InterruptedException
 *         if the current thread was interrupted while waiting
 * @throws Exception
 *         if the computation threw an exception
 */
public static <T> T invokeNow(Callable<T> callable) throws InterruptedException, Exception {
    if (SwingUtilities.isEventDispatchThread())
        return callable.call();

    final FutureTask<T> task = new FutureTask<T>(callable);

    try {
        EventQueue.invokeAndWait(task);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof Exception)
            throw (Exception) e.getCause();

        // not an exception --> handle it
        //IcyExceptionHandler.showErrorMessage(e, true);
        return null;
    }

    try {
        return task.get();
    } catch (ExecutionException e) {
        if (e.getCause() instanceof Exception)
            throw (Exception) e.getCause();

        // not an exception --> handle it
        //IcyExceptionHandler.showErrorMessage(e, true);
        return null;
    }
}