java.util.concurrent.ExecutorService.submit()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(160)

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

ExecutorService.submit介绍

[英]Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return null upon successful completion.
[中]提交可运行任务以执行,并返回表示该任务的Future。Future的get方法在成功完成后将返回null。

代码示例

代码示例来源:origin: aws/aws-sdk-java

public void submit(GeneratorTask task) {
  if (DEBUG) {
    try {
      task.call();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  } else {
    futures.add(executor.submit(task));
  }
}

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

@Deprecated
  public static <T> Future<T> future( final Callable<T> task )
  {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<T> future = executor.submit( task );
    executor.shutdown();
    return future;
  }
}

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

final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
 producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

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

@Test
public void testGetInputPathsPool() throws IOException, ExecutionException, InterruptedException {
 List<Path> pathsToAdd = new ArrayList<>();
 Path path = new Path("dummy-path");
 pathsToAdd.add(path);
 pathsToAdd.add(path);
 pathsToAdd.add(path);
 ExecutorService pool = mock(ExecutorService.class);
 Future mockFuture = mock(Future.class);
 when(mockFuture.get()).thenReturn(path);
 when(pool.submit(any(Callable.class))).thenReturn(mockFuture);
 Utilities.getInputPathsWithPool(mock(JobConf.class), mock(MapWork.class), mock(Path.class), mock(Context.class),
     false, pathsToAdd, pool);
 verify(pool, times(3)).submit(any(Callable.class));
 verify(pool).shutdown();
 verify(pool).shutdownNow();
}

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

@Test
public void testCheckQuotasInMultiThreads() throws InterruptedException, ExecutionException {
  final Metrics metrics = new Metrics(new MetricConfig().quota(Quota.upperBound(Double.MAX_VALUE))
  final int threadCount = 10;
  final CountDownLatch latch = new CountDownLatch(1);
  ExecutorService service = Executors.newFixedThreadPool(threadCount);
  List<Future<Throwable>> workers = new ArrayList<>(threadCount);
  boolean needShutdown = true;
    for (int i = 0; i != threadCount; ++i) {
      final int index = i;
      workers.add(service.submit(new Callable<Throwable>() {
        @Override
        public Throwable call() {
    service.shutdown();
    assertTrue(service.awaitTermination(10, TimeUnit.SECONDS));
    needShutdown = false;
    for (Future<Throwable> callable : workers) {
      assertTrue("If this failure happen frequently, we can try to increase the wait time", callable.isDone());
      assertNull("Sensor#checkQuotas SHOULD be thread-safe!", callable.get());

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

private void llapCachePurge(final SessionState ss, final LlapRegistryService llapRegistryService) throws Exception {
 ExecutorService executorService = Executors.newCachedThreadPool();
 List<Future<Long>> futures = new ArrayList<>();
 Collection<LlapServiceInstance> instances = llapRegistryService.getInstances().getAll();
 for (LlapServiceInstance instance : instances) {
  futures.add(executorService.submit(new PurgeCallable(ss.getConf(), instance)));
 }
 int i = 0;
 for (LlapServiceInstance instance : instances) {
  Future<Long> future = futures.get(i);
  ss.out.println(Joiner.on("\t").join(instance.getHost(), future.get()));
  i++;
 }
}

代码示例来源:origin: apache/incubator-druid

@Test
public void testLoadSegment() throws ExecutionException, InterruptedException, SegmentLoadingException
{
 final List<Future<Boolean>> futures = segments.stream()
                        .map(
                          segment -> executor.submit(
                            () -> segmentManager.loadSegment(segment)
                          )
                        )
                        .collect(Collectors.toList());
 for (Future<Boolean> eachFuture : futures) {
  Assert.assertTrue(eachFuture.get());
 }
 assertResult(segments);
}

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

@Test
public void testTimeoutAndRetryJoinGroupIfNeeded() throws Exception {
  setupCoordinator();
  mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
  coordinator.ensureCoordinatorReady(mockTime.timer(0));
  ExecutorService executor = Executors.newFixedThreadPool(1);
  try {
    Timer firstAttemptTimer = mockTime.timer(REQUEST_TIMEOUT_MS);
    Future<Boolean> firstAttempt = executor.submit(() -> coordinator.joinGroupIfNeeded(firstAttemptTimer));
    mockTime.sleep(REQUEST_TIMEOUT_MS);
    assertFalse(firstAttempt.get());
    assertTrue(consumerClient.hasPendingRequests(coordinatorNode));
    mockClient.respond(joinGroupFollowerResponse(1, "memberId", "leaderId", Errors.NONE));
    mockClient.prepareResponse(syncGroupResponse(Errors.NONE));
    Timer secondAttemptTimer = mockTime.timer(REQUEST_TIMEOUT_MS);
    Future<Boolean> secondAttempt = executor.submit(() -> coordinator.joinGroupIfNeeded(secondAttemptTimer));
    assertTrue(secondAttempt.get());
  } finally {
    executor.shutdownNow();
    executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
  }
}

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

@Test(timeout = 5000)
public void fromFutureNormal() {
  ExecutorService exec = Executors.newSingleThreadExecutor();
  try {
    Completable c = Completable.fromFuture(exec.submit(new Runnable() {
      @Override
      public void run() {
        // no action
      }
    }));
    c.blockingAwait();
  } finally {
    exec.shutdown();
  }
}

代码示例来源:origin: google/guava

@Override
public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
  throws TimeoutException, InterruptedException {
 checkNotNull(runnable);
 checkNotNull(timeoutUnit);
 checkPositiveTimeout(timeoutDuration);
 Future<?> future = executor.submit(runnable);
 try {
  future.get(timeoutDuration, timeoutUnit);
 } catch (InterruptedException | TimeoutException e) {
  future.cancel(true /* mayInterruptIfRunning */);
  throw e;
 } catch (ExecutionException e) {
  wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
  throw new AssertionError();
 }
}

代码示例来源:origin: google/j2objc

public void run() {
    ExecutorService service = Executors.newSingleThreadExecutor();
    Callable<Object> callable = new Callable<Object>() {
      public Object call() throws Exception {
        runTestMethod();
        return null;
      }
    };
    Future<Object> result = service.submit(callable);
    service.shutdown();
    try {
      boolean terminated = service.awaitTermination(timeout,
          TimeUnit.MILLISECONDS);
      if (!terminated) {
        service.shutdownNow();
      }
      result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation
    } catch (TimeoutException e) {
      addFailure(new Exception(String.format("test timed out after %d milliseconds", timeout)));
    } catch (Exception e) {
      addFailure(e);
    }
  }
});

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

ExecutorService exec = Executors.newFixedThreadPool(SOME_NUM_OF_THREADS);
try {
  for (final Object o : list) {
    exec.submit(new Runnable() {
      @Override
      public void run() {
        // do stuff with o.
      }
    });
  }
} finally {
  exec.shutdown();
}

代码示例来源:origin: aws/aws-sdk-java

@Override
public java.util.concurrent.Future<AcceptVpcEndpointConnectionsResult> acceptVpcEndpointConnectionsAsync(final AcceptVpcEndpointConnectionsRequest request,
    final com.amazonaws.handlers.AsyncHandler<AcceptVpcEndpointConnectionsRequest, AcceptVpcEndpointConnectionsResult> asyncHandler) {
  final AcceptVpcEndpointConnectionsRequest finalRequest = beforeClientExecution(request);
  return executorService.submit(new java.util.concurrent.Callable<AcceptVpcEndpointConnectionsResult>() {
    @Override
    public AcceptVpcEndpointConnectionsResult call() throws Exception {
      AcceptVpcEndpointConnectionsResult result = null;
      try {
        result = executeAcceptVpcEndpointConnections(finalRequest);
      } catch (Exception ex) {
        if (asyncHandler != null) {
          asyncHandler.onError(ex);
        }
        throw ex;
      }
      if (asyncHandler != null) {
        asyncHandler.onSuccess(finalRequest, result);
      }
      return result;
    }
  });
}

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

ExecutorService service = Executors.newSingleThreadExecutor();

try {
  Runnable r = new Runnable() {
    @Override
    public void run() {
      // Database task
    }
  };

  Future<?> f = service.submit(r);

  f.get(2, TimeUnit.MINUTES);     // attempt the task for two minutes
}
catch (final InterruptedException e) {
  // The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
  // Took too long!
}
catch (final ExecutionException e) {
  // An exception from within the Runnable task
}
finally {
  service.shutdown();
}

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

class TaskAsCallable implements Callable<Result> {
  @Override
  public Result call() {
    return a new Result() // this is where the work is done.
  }
}

ExecutorService executor = Executors.newFixedThreadPool(300);
Future<Result> task = executor.submit(new TaskAsCallable());
Result result = task.get(); // this blocks until result is ready

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

private static void shutdownDbExecutor(ExecutorService executorService, Collection<SQLiteConnection> connections) {
 for (final SQLiteConnection connection : connections) {
  getFuture("close connection on reset", executorService.submit(new Callable<Void>() {
   @Override
   public Void call() throws Exception {
    connection.dispose();
    return null;
   }
  }));
 }
 executorService.shutdown();
 try {
  executorService.awaitTermination(30, TimeUnit.SECONDS);
 } catch (InterruptedException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: google/guava

/** Runs {@code callable} concurrently {@code numberOfThreads} times. */
 @GwtIncompatible // concurrency
 private void runConcurrentTest(int numberOfThreads, final Callable<Void> callable)
   throws Exception {
  ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
  final CountDownLatch startLatch = new CountDownLatch(numberOfThreads);
  final CountDownLatch doneLatch = new CountDownLatch(numberOfThreads);
  for (int i = numberOfThreads; i > 0; i--) {
   @SuppressWarnings("unused") // go/futurereturn-lsc
   Future<?> possiblyIgnoredError =
     executorService.submit(
       new Callable<Void>() {
        @Override
        public Void call() throws Exception {
         startLatch.countDown();
         startLatch.await();
         callable.call();
         doneLatch.countDown();
         return null;
        }
       });
  }
  doneLatch.await();
 }
}

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

ExecutorService pool = Executors.newFixedThreadPool(10);
for (String name : fileNames) {
  pool.submit(new DownloadTask(name, toPath));
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// all tasks have now finished (unless an exception is thrown above)

代码示例来源:origin: TooTallNate/Java-WebSocket

protected void consumeDelegatedTasks() {
  Runnable task;
  while ( ( task = sslEngine.getDelegatedTask() ) != null ) {
    tasks.add( exec.submit( task ) );
    // task.run();
  }
}

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

private void applyBatchesInParallel( ParallelNativeIndexPopulator<GenericKey,NativeIndexValue> populator, int batchCountPerThread )
    throws ExecutionException, InterruptedException
{
  CountDownLatch startSignal = new CountDownLatch( THREADS );
  List<Future<Void>> futures = new ArrayList<>();
  for ( int i = 0; i < THREADS; i++ )
  {
    futures.add( executorService.submit( () ->
    {
      // Wait for all to get into pole position, this is because we want to make sure all threads are used.
      startSignal.countDown();
      startSignal.await();
      for ( int j = 0; j < batchCountPerThread; j++ )
      {
        populator.add( asList( update( next.getAndIncrement() ) ) );
      }
      return null;
    } ) );
  }
  for ( Future<Void> future : futures )
  {
    future.get();
  }
}

相关文章