Java Thread Callable runWithTimeout(long millisTimeout, Callable callable)

Here you can find the source of runWithTimeout(long millisTimeout, Callable callable)

Description

Runs and blocking waits for the given callable to finish for the given time.

License

Open Source License

Parameter

Parameter Description
millisTimeout a parameter
callable a parameter

Declaration

public static <R> R runWithTimeout(long millisTimeout,
        Callable<R> callable) 

Method Source Code

//package com.java2s;
/******************************************************************************* 
 * Copyright (c) 2015 Red Hat, Inc. //from  w  w w  .  j  ava  2s  .co m
 * Distributed under license by Red Hat, Inc. All rights reserved. 
 * This program is made available under the terms of the 
 * Eclipse Public License v1.0 which accompanies this distribution, 
 * and is available at http://www.eclipse.org/legal/epl-v10.html 
 * 
 * Contributors:
 *     Red Hat Incorporated - initial API and implementation
 ******************************************************************************/

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Main {
    /**
     * Runs and blocking waits for the given callable to finish for the given
     * time. Returns <code>null</code> if timeouts waiting for callable value.
     * 
     * @param millisTimeout
     * @param callable
     * @return
     */
    public static <R> R runWithTimeout(long millisTimeout,
            Callable<R> callable) {
        ExecutorService singleThreadExecutor = Executors
                .newFixedThreadPool(1);
        Future<R> future = singleThreadExecutor.submit(callable);
        try {
            return future.get(millisTimeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException
                | TimeoutException e) {
        } finally {
            singleThreadExecutor.shutdown();
        }
        return null;
    }
}

Related

  1. runConcurrently(final Callable task)
  2. runConcurrently(final Callable task)
  3. runConcurrently(final Callable task, final int times)
  4. runInBackground(final Callable callable)
  5. runTest(Callable test)
  6. shuffleRow(final double[] data)
  7. submitAndWait(ListeningExecutorService service, Callable ca)
  8. submitManyAndWait(ListeningExecutorService service, Iterable> cas, FutureCallback fca)
  9. sum(final double[] a)