java.util.concurrent.FutureTask类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.0k)|赞(0)|评价(0)|浏览(112)

本文整理了Java中java.util.concurrent.FutureTask类的一些代码示例,展示了FutureTask类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FutureTask类的具体详情如下:
包路径:java.util.concurrent.FutureTask
类名称:FutureTask

FutureTask介绍

[英]A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the getmethods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using #runAndReset).

A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.

In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.
[中]一种可取消的异步计算。此类提供了Future的基本实现,其中包含启动和取消计算、查询以查看计算是否完成以及检索计算结果的方法。只有在计算完成后才能检索结果;如果计算尚未完成,getmethods将阻塞。计算完成后,无法重新启动或取消计算(除非使用#runAndReset调用计算)。
FutureTask可用于包装可调用或可运行的对象。因为FutureTask实现Runnable,所以FutureTask可以提交给执行者执行。
除了作为独立类之外,该类还提供了受保护的功能,这些功能在创建自定义任务类时可能很有用。

代码示例

代码示例来源:origin: org.apache.commons/commons-lang3

public O compute(final I arg) throws InterruptedException {
  while (true) {
    Future<O> future = cache.get(arg);
    if (future == null) {
      final Callable<O> eval = new Callable<O>() {
      final FutureTask<O> futureTask = new FutureTask<>(eval);
      future = cache.putIfAbsent(arg, futureTask);
      if (future == null) {
        future = futureTask;
        futureTask.run();
      return future.get();
    } catch (final CancellationException e) {
      cache.remove(arg, future);
    } catch (final ExecutionException e) {
      if (recalculate) {
      throw launderException(e.getCause());

代码示例来源:origin: org.easymock/easymock

task = new FutureTask<V>(new Callable<V>() {
    public V call() throws Exception {
      return loader.apply(key);
  Object prevTask = map.putIfAbsent(cacheKey, task);
  if (prevTask == null) {
    task.run();
  } else if (prevTask instanceof FutureTask) {
    task = (FutureTask<V>) prevTask;
  result = task.get();
} catch (InterruptedException e) {
  throw new IllegalStateException("Interrupted while loading cache item", e);
} catch (ExecutionException e) {
  Throwable cause = e.getCause();
  if (cause instanceof RuntimeException) {
    throw ((RuntimeException) cause);
  map.put(cacheKey, result);

代码示例来源:origin: skylot/jadx

@Override
  public boolean cancel(boolean mayInterruptIfRunning) {
    executor.shutdownNow();
    return super.cancel(mayInterruptIfRunning);
  }
}

代码示例来源:origin: airbnb/lottie-android

@Override public void run() {
  while (true) {
   if (isInterrupted() || taskComplete) {
    return;
   }
   if (task.isDone()) {
    try {
     setResult(task.get());
    } catch (InterruptedException | ExecutionException e) {
     setResult(new LottieResult<T>(e));
    }
    taskComplete = true;
    stopTaskObserverIfNeeded();
   }
  }
 }
};

代码示例来源:origin: ReactiveX/RxJava

@Override
public Publisher<Long> createPublisher(final long elements) {
  FutureTask<Long> ft = new FutureTask<Long>(new Callable<Long>() {
    @Override
    public Long call() throws Exception {
      return 1L;
    }
  });
  ft.run();
  return Flowable.fromFuture(ft);
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void disposeOnCurrentThread() throws Exception {
  ExecutorService exec = Executors.newSingleThreadExecutor();
  try {
    InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() {
      @Override
      public void run() {
        throw new TestException();
      }
    }, exec);
    task.runner = Thread.currentThread();
    task.dispose();
    FutureTask<Void> f1 = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null);
    task.setFirst(f1);
    assertTrue(f1.isCancelled());
    FutureTask<Void> f2 = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null);
    task.setRest(f2);
    assertTrue(f2.isCancelled());
  } finally {
    exec.shutdownNow();
    RxJavaPlugins.reset();
  }
}

代码示例来源:origin: apache/hive

FutureTask<Integer> evictionTask = new FutureTask<Integer>(new Callable<Integer>() {
 public Integer call() {
  boolean isFirstFile = false;
FutureTask<Long> rdmTask1 = new FutureTask<Long>(rdmCall),
  rdmTask2 = new FutureTask<Long>(rdmCall), rdmTask3 = new FutureTask<Long>(rdmCall);
Executor threadPool = Executors.newFixedThreadPool(4);
threadPool.execute(rdmTask1);
threadPool.execute(rdmTask2);
threadPool.execute(rdmTask3);
threadPool.execute(evictionTask);
try {
 cdlIn.await();
 cdlOut.countDown();
 long result1 = rdmTask1.get(), result2 = rdmTask2.get(), result3 = rdmTask3.get();
 int evictions = evictionTask.get();
 LOG.info("MTT test: task 1: " + descRdmTask(result1)  + ", task 2: " + descRdmTask(result2)
   + ", task 3: " + descRdmTask(result3) + "; " + evictions + " evictions");

代码示例来源:origin: stackoverflow.com

ExecutorService executor = Executors.newFixedThreadPool();
FutureTask<Object> futureOne = new FutureTask<Object>(myFirstProcess);
FutureTask<Object> futureTwo = new FutureTask<Object>(mySecondProcess);
executor.execute(futureOne);
executor.execute(futureTwo);
executor.shutdown();
try {
 executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
 // interrupted
}

代码示例来源:origin: apache/hbase

Future<?> future = executor.submit(getRegionStoreFileMapCall);
 futures.add(future);
} else {
 FutureTask<?> future = new FutureTask<>(getRegionStoreFileMapCall, null);
 future.run();
 futures.add(future);
 f.get();
} catch (ExecutionException e) {
 LOG.error("Unexpected exec exception!  Should've been caught already.  (Bug?)", e);

代码示例来源:origin: spring-projects/spring-framework

@Override
public <T> Future<T> submit(Callable<T> task) {
  try {
    if (this.taskDecorator == null && this.concurrentExecutor instanceof ExecutorService) {
      return ((ExecutorService) this.concurrentExecutor).submit(task);
    }
    else {
      FutureTask<T> future = new FutureTask<>(task);
      doExecute(this.concurrentExecutor, this.taskDecorator, future);
      return future;
    }
  }
  catch (RejectedExecutionException ex) {
    throw new TaskRejectedException(
        "Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex);
  }
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void dispose2CurrentThread() throws Exception {
  ExecutorService exec = Executors.newSingleThreadExecutor();
  try {
    InstantPeriodicTask task = new InstantPeriodicTask(new Runnable() {
      @Override
      public void run() {
        throw new TestException();
      }
    }, exec);
    task.runner = Thread.currentThread();
    task.setFirst(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null));
    task.setRest(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null));
    assertFalse(task.isDisposed());
    task.dispose();
    assertTrue(task.isDisposed());
    task.dispose();
    assertTrue(task.isDisposed());
  } finally {
    exec.shutdownNow();
    RxJavaPlugins.reset();
  }
}

代码示例来源:origin: goldmansachs/gs-collections

final int end = Math.min((i + 1) * chunkSize, currentArray.length);
final Procedure2<K, V> block = blocks.get(i);
futures[i] = new FutureTask<Void>(new Runnable()
executor.execute(futures[i]);
  futures[i].get();

代码示例来源:origin: spring-projects/spring-batch

final FutureTask<FlowExecution> task = new FutureTask<>(new Callable<FlowExecution>() {
  @Override
  public FlowExecution call() throws Exception {
  results.add(task.get());
  Throwable cause = e.getCause();
  if (cause instanceof Exception) {
    throw (Exception) cause;

代码示例来源:origin: apache/hive

@Test(timeout = 200000)
public void testMtt() {
 final int baseAllocSizeLog2 = 3, maxAllocSizeLog2 = 10, totalSize = 8192,
   baseAllocSize = 1 << baseAllocSizeLog2, maxAllocSize = 1 << maxAllocSizeLog2;
 final int threadCount = maxAllocSizeLog2 - baseAllocSizeLog2 + 1;
 final int iterCount = 500;
 final BuddyAllocator a = create(maxAllocSize, 4, totalSize, true, false);
 ExecutorService executor = Executors.newFixedThreadPool(threadCount + 1);
 CountDownLatch cdlIn = new CountDownLatch(threadCount), cdlOut = new CountDownLatch(1);
 @SuppressWarnings("unchecked")
 FutureTask<MttTestCallableResult>[] allocTasks = new FutureTask[threadCount];
 FutureTask<Void> dumpTask = createAllocatorDumpTask(a);
 for (int allocSize = baseAllocSize, i = 0; allocSize <= maxAllocSize; allocSize <<= 1, ++i) {
  allocTasks[i] = new FutureTask<>(new MttTestCallable(
    cdlIn, cdlOut, a, allocSize, totalSize / allocSize, iterCount));
  executor.execute(allocTasks[i]);
 }
 executor.execute(dumpTask);
 runMttTest(a, allocTasks, cdlIn, cdlOut, dumpTask, null, null, totalSize, maxAllocSize);
}

代码示例来源:origin: junit-team/junit4

/**
 * Wait for the test task, returning the exception thrown by the test if the
 * test failed, an exception indicating a timeout if the test timed out, or
 * {@code null} if the test passed.
 */
private Throwable getResult(FutureTask<Throwable> task, Thread thread) {
  try {
    if (timeout > 0) {
      return task.get(timeout, timeUnit);
    } else {
      return task.get();
    }
  } catch (InterruptedException e) {
    return e; // caller will re-throw; no need to call Thread.interrupt()
  } catch (ExecutionException e) {
    // test failed; have caller re-throw the exception thrown by the test
    return e.getCause();
  } catch (TimeoutException e) {
    return createTimeoutException(thread);
  }
}

代码示例来源:origin: stackoverflow.com

RunnableFuture f = new FutureTask(new Callable<Boolean>() {
 // implement call
});
// start the thread to execute it (you may also use an Executor)
new Thread(f).start();
// get the result
f.get();

代码示例来源:origin: neo4j/neo4j

@Test
  void combinedFutureShouldGetResultsAfterAllComplete() throws Exception
  {
    FutureTask<String> task1 = new FutureTask<>( NOOP, "1" );
    FutureTask<String> task2 = new FutureTask<>( NOOP, "2" );
    FutureTask<String> task3 = new FutureTask<>( NOOP, "3" );

    Future<List<String>> combined = Futures.combine( task1, task2, task3 );

    assertThrows( TimeoutException.class, () -> combined.get( 10, TimeUnit.MILLISECONDS ) );

    task3.run();
    task2.run();

    assertThrows( TimeoutException.class, () -> combined.get( 10, TimeUnit.MILLISECONDS ) );

    task1.run();

    List<String> result = combined.get();
    assertThat( result, contains( "1", "2", "3" ) );
  }
}

代码示例来源:origin: stackoverflow.com

private static final ExecutorService THREAD_POOL 
  = Executors.newCachedThreadPool();

private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
  throws InterruptedException, ExecutionException, TimeoutException
{
  FutureTask<T> task = new FutureTask<T>(c);
  THREAD_POOL.execute(task);
  return task.get(timeout, timeUnit);
}

try {
  int returnCode = timedCall(new Callable<Integer>() {
    public Integer call() throws Exception {
      java.lang.Process process = Runtime.getRuntime().exec(command); 
      return process.waitFor();
    }
  }, timeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
  // Handle timeout here
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void defaultExecutor() throws Exception {
  ApplicationContext context = new AnnotationConfigApplicationContext(ExecutorConfig.class);
  ExecutorService executor = context.getBean("executor", ExecutorService.class);
  FutureTask<String> task = new FutureTask<>(new Callable<String>() {
    @Override
    public String call() throws Exception {
      return "foo";
    }
  });
  executor.execute(task);
  assertEquals("foo", task.get());
}

代码示例来源:origin: facebook/litho

LayoutState runAndGet() {
 if (runningThreadId.compareAndSet(-1, Process.myTid())) {
  futureTask.run();
 LithoAffinityBooster booster = null;
 if (isMainThread() && !futureTask.isDone() && runningThreadId != Process.myTid()) {
  result = futureTask.get();
 } catch (ExecutionException e) {
  final Throwable cause = e.getCause();
  if (cause instanceof RuntimeException) {
   throw (RuntimeException) cause;
  } else {
   throw new RuntimeException(e.getMessage(), e);

相关文章