ExecutorService taskExecutor = Executors.newFixedThreadPool(4); List<Callable<?>> tasks; // your tasks // invokeAll() returns when all tasks are complete List<Future<?>> futures = taskExecutor.invokeAll(tasks);
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();
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);
/** * 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()); } } }
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);
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) {
@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; }
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();
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();
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();
/** * 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()); } } } }
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; } }
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; }
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() {
/** * 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); }
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);
/** * @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(); }