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

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

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

ExecutorService.invokeAll介绍

[英]Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future#isDone is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.
[中]执行给定的任务,当所有任务完成时,返回一个保存其状态和结果的未来列表。对于返回列表的每个元素,Future#isDone都为true。请注意,已完成任务可以正常终止,也可以通过引发异常终止。如果在执行此操作时修改了给定集合,则此方法的结果是未定义的。

代码示例

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

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete
List<Future<?>> futures = taskExecutor.invokeAll(tasks);

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

final ExecutorService pool = Executors.newFixedThreadPool(2);
final List<? extends Callable<String>> callables = Arrays.asList(
  new SleepingCallable("quick", 500),
  new SleepingCallable("slow", 5000));
try {
 for (final Future<String> future : pool.invokeAll(callables)) {
  System.out.println(future.get());
 }
} catch (ExecutionException | InterruptedException ex) { }
pool.shutdown();

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

ExecutorService es = Executors.newFixedThreadPool(2);
List<Callable<Object>> todo = new ArrayList<Callable<Object>>(singleTable.size());

for (DataTable singleTable: uniquePhrases) { 
  todo.add(Executors.callable(new ComputeDTask(singleTable))); 
}

List<Future<Object>> answers = es.invokeAll(todo);

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

/**
 * Contacts each regionserver and fetches metadata about regions.
 * @param regionServerList - the list of region servers to connect to
 * @throws IOException if a remote or network exception occurs
 */
void processRegionServers(Collection<ServerName> regionServerList)
 throws IOException, InterruptedException {
 List<WorkItemRegion> workItems = new ArrayList<>(regionServerList.size());
 List<Future<Void>> workFutures;
 // loop to contact each region server in parallel
 for (ServerName rsinfo: regionServerList) {
  workItems.add(new WorkItemRegion(this, rsinfo, errors, connection));
 }
 workFutures = executor.invokeAll(workItems);
 for(int i=0; i<workFutures.size(); i++) {
  WorkItemRegion item = workItems.get(i);
  Future<Void> f = workFutures.get(i);
  try {
   f.get();
  } catch(ExecutionException e) {
   LOG.warn("Could not process regionserver " + item.rsinfo.getHostAndPort(),
     e.getCause());
  }
 }
}

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

ExecutorService EXEC = Executors.newCachedThreadPool();
List<Callable<Result>> tasks = new ArrayList<Callable<Result>>();
for (final Object object: objects) {
  Callable<Result> c = new Callable<Result>() {
    @Override
    public Result call() throws Exception {
      return compute(object);
    }
  };
  tasks.add(c);
}
List<Future<Result>> results = EXEC.invokeAll(tasks);

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

preferredNodes.add(node);
    else
      extraNodes.add(node);
      nodeToKeysMap.put(node, nodeKeys);
    nodeKeys.add(key);
  futures = executor.invokeAll(callables, timeoutMs * 3, TimeUnit.MILLISECONDS);
} catch(InterruptedException e) {
  throw new InsufficientOperationalNodesException("getAll operation interrupted.", e);
    GetAllResult getResult = f.get();
    if(getResult.exception != null) {
      if(getResult.exception instanceof VoldemortApplicationException) {

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

callables.add(new Callable<Object>() {
  pooledExecutor.invokeAll(callables, timeout, TimeUnit.MILLISECONDS);
 } else {
  pooledExecutor.invokeAll(callables);
 Thread.currentThread().interrupt();
} finally {
 pooledExecutor.shutdown();

代码示例来源:origin: languagetool-org/languagetool

@Override
protected List<RuleMatch> performCheck(List<AnalyzedSentence> analyzedSentences, List<String> sentences,
   List<Rule> allRules, ParagraphHandling paraMode, 
   AnnotatedText annotatedText, RuleMatchListener listener, Mode mode) {
 int charCount = 0;
 int lineCount = 0;
 int columnCount = 1;
 List<RuleMatch> ruleMatches = new ArrayList<>();
 
 ExecutorService executorService = getExecutorService();
 try {
  List<Callable<List<RuleMatch>>> callables =
      createTextCheckCallables(paraMode, annotatedText, analyzedSentences, sentences, allRules, charCount, lineCount, columnCount, listener, mode);
  List<Future<List<RuleMatch>>> futures = executorService.invokeAll(callables);
  for (Future<List<RuleMatch>> future : futures) {
   ruleMatches.addAll(future.get());
  }
 } catch (InterruptedException | ExecutionException e) {
  throw new RuntimeException(e);
 }
 
 return ruleMatches;
}

代码示例来源:origin: jeremylong/DependencyCheck

final List<Future<Void>> results = executorService.invokeAll(analysisTasks, timeout, TimeUnit.MINUTES);
      result.get();
    } catch (ExecutionException e) {
      throwFatalExceptionCollection("Analysis task failed with a fatal exception.", e, exceptions);
  throwFatalExceptionCollection("Analysis has been interrupted.", e, exceptions);
} finally {
  executorService.shutdown();

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

ExecutorService pool = Executors.newFixedThreadPool(10);
 List<Future<List<StudentsResults>>> sresults = pool.invokeAll(stasks);
 List<Future<List<DoctorsResults>>> dresults = pool.invokeAll(dtasks);
 List<Future<List<PatientsResults>>> presults = pool.invokeAll(ptasks);
   this.patientsResults.addAll(future.get());
 pool.shutdown();

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

ExecutorService pool = Executors.newFixedThreadPool(10);
 List<Callable<String>> tasks = new ArrayList<>();
 tasks.add(new Callable<String>() {
   public String call() throws Exception {
     Thread.sleep((new Random().nextInt(5000)) + 500);
     return "Hello world";
   }
 });
 List<Future<String>> results = pool.invokeAll(tasks);
 for (Future<String> future : results) {
   System.out.println(future.get());
 }
 pool.shutdown();

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

/**
 * Check consistency of all regions using mulitple threads concurrently.
 */
private void checkRegionConsistencyConcurrently(
 final List<CheckRegionConsistencyWorkItem> workItems)
 throws IOException, KeeperException, InterruptedException {
 if (workItems.isEmpty()) {
  return;  // nothing to check
 }
 List<Future<Void>> workFutures = executor.invokeAll(workItems);
 for(Future<Void> f: workFutures) {
  try {
   f.get();
  } catch(ExecutionException e1) {
   LOG.warn("Could not check region consistency " , e1.getCause());
   if (e1.getCause() instanceof IOException) {
    throw (IOException)e1.getCause();
   } else if (e1.getCause() instanceof KeeperException) {
    throw (KeeperException)e1.getCause();
   } else if (e1.getCause() instanceof InterruptedException) {
    throw (InterruptedException)e1.getCause();
   } else {
    throw new IOException(e1.getCause());
   }
  }
 }
}

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

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.MINUTES); // Timeout of 10 minutes.
executor.shutdown();

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

public Collection<ResponseInfo> executeAll() throws InterruptedException, ExecutionException {

    Collection<Job> jobs = new HashSet<Job>( sshValues.size() );
    for( SshValues sshValue: sshValues ) {
      jobs.add( new Job( commands, sshValue ) );
    }

    ExecutorService service = Executors.newFixedThreadPool( sshValues.size() + 1 );
    List<Future<ResponseInfo>> futureResponses = service.invokeAll( jobs );
    service.shutdown();

    Collection<ResponseInfo> responses = new ArrayList<ResponseInfo>( sshValues.size() );

    for( Future<ResponseInfo> response: futureResponses ) {
      responses.add( response.get() );
    }
    return responses;
  }
}

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

private boolean handleOverlapsParallel(TableIntegrityErrorHandler handler, byte[] prevKey)
  throws IOException {
 // we parallelize overlap handler for the case we have lots of groups to fix.  We can
 // safely assume each group is independent.
 List<WorkItemOverlapMerge> merges = new ArrayList<>(overlapGroups.size());
 List<Future<Void>> rets;
 for (Collection<HbckInfo> overlap : overlapGroups.asMap().values()) {
  //
  merges.add(new WorkItemOverlapMerge(overlap, handler));
 }
 try {
  rets = executor.invokeAll(merges);
 } catch (InterruptedException e) {
  LOG.error("Overlap merges were interrupted", e);
  return false;
 }
 for(int i=0; i<merges.size(); i++) {
  WorkItemOverlapMerge work = merges.get(i);
  Future<Void> f = rets.get(i);
  try {
   f.get();
  } catch(ExecutionException e) {
   LOG.warn("Failed to merge overlap group" + work, e.getCause());
  } catch (InterruptedException e) {
   LOG.error("Waiting for overlap merges was interrupted", e);
   return false;
  }
 }
 return true;
}

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

private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();
private static final ExecutorService forPool = Executors.newFixedThreadPool(NUM_CORES * 2, new NamedThreadFactory("Parallel.For"));
    forPool.invokeAll(createCallables(elements, operation));
  } catch (InterruptedException e) {
    e.printStackTrace();
  List<Callable<Void>> callables = new LinkedList<Callable<Void>>();
  for (final T elem : elements) {
    callables.add(new Callable<Void>() {
      @Override
      public Void call() {

代码示例来源:origin: Netflix/zuul

/**
 * puts files into the FilterLoader. The FilterLoader will only add new or changed filters
 *
 * @param aFiles a List<File>
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
void processGroovyFiles(List<File> aFiles) throws Exception {
  List<Callable<Boolean>> tasks = new ArrayList<>();
  for (File file : aFiles) {
    tasks.add(() -> {
      try {
        return filterLoader.putFilter(file);
      }
      catch(Exception e) {
        LOG.error("Error loading groovy filter from disk! file = " + String.valueOf(file), e);
        return false;
      }
    });
  }
  processFilesService.invokeAll(tasks, FILE_PROCESSOR_TASKS_TIMEOUT_SECS.get(), TimeUnit.SECONDS);
}

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

for(; nodeIndex < attempts; nodeIndex++) {
  final Node node = nodes.get(nodeIndex);
  callables.add(new GetCallable<R>(node, key, transforms, fetcher));
                    : timeoutConfig.getOperationTimeout(VoldemortOpCode.GET_OP_CODE);
try {
  futures = executor.invokeAll(callables, timeoutMs, TimeUnit.MILLISECONDS);
} catch(InterruptedException e) {
  throw new InsufficientOperationalNodesException("Get operation interrupted!", e);
    GetResult<R> getResult = f.get();
    if(getResult.exception != null) {
      if(getResult.exception instanceof VoldemortApplicationException) {
        throw (VoldemortException) getResult.exception;
      failures.add(getResult.exception);
      continue;
    retrieved.add(getResult);
  } catch(InterruptedException e) {
    throw new InsufficientOperationalNodesException("Get operation interrupted!", e);

代码示例来源:origin: cbeust/testng

callables.add(
   () -> {
    task.run();
  pooledExecutor.invokeAll(callables, timeout, TimeUnit.MILLISECONDS);
 } else {
  pooledExecutor.invokeAll(callables);
 Thread.currentThread().interrupt();
} finally {
 pooledExecutor.shutdown();

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

/**
 * @throws Exception Thrown in case of test failure.
 */
@SuppressWarnings("TooBroadScope")
@Test
public void testInvokeAll() throws Exception {
  Ignite ignite = G.ignite(getTestIgniteInstanceName());
  ExecutorService srvc = createExecutorService(ignite);
  Collection<Callable<String>> cmds = new ArrayList<>(2);
  String val1 = "test-value-1";
  String val2 = "test-value-2";
  cmds.add(new TestCallable<>(val1));
  cmds.add(new TestCallable<>(val2));
  List<Future<String>> futs = srvc.invokeAll(cmds);
  assert futs != null;
  assert futs.size() == 2;
  String res1 = futs.get(0).get();
  String res2 = futs.get(1).get();
  assert val1.equals(res1) : "Failed to get valid result for first command: " + res1;
  assert val2.equals(res2) : "Failed to get valid result for second command: " + res2;
  srvc.shutdown();
}

相关文章