List of usage examples for java.util.concurrent Future get
V get() throws InterruptedException, ExecutionException;
From source file:com.apm4all.tracy.TracyAsyncHttpClientPublisher.java
@Override public boolean publish(String tracySegment) { boolean published = true; HttpPost httpPost;// w ww . jav a 2 s .c o m if (null != this.uri) { if (httpProxyConfig.isEnabled()) { HttpHost proxy = new HttpHost(httpProxyConfig.getHost(), httpProxyConfig.getPort(), "http"); RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).setAuthenticationEnabled(true) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); httpPost = new HttpPost(uri); httpPost.setConfig(reqConfig); } else { httpPost = new HttpPost(uri); } StringEntity se; try { se = new StringEntity(tracySegment, StandardCharsets.UTF_8); se.setContentType(MediaType.APPLICATION_JSON); httpPost.setEntity(se); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, TRACY_CONTENT_TYPE); Future<HttpResponse> future = httpClient.execute(httpPost, null); if (waitForResponse) { HttpResponse response = future.get(); published = (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK); if (debug) { System.out.println(extractPostResponse(response)); } } } catch (Exception e) { } } return published; }
From source file:com.networknt.limit.LimitHandlerTest.java
@Test public void testMoreRequests() throws Exception { Callable<String> task = this::callApi; List<Callable<String>> tasks = Collections.nCopies(10, task); long start = System.currentTimeMillis(); ExecutorService executorService = Executors.newFixedThreadPool(10); List<Future<String>> futures = executorService.invokeAll(tasks); List<String> resultList = new ArrayList<>(futures.size()); // Check for exceptions for (Future<String> future : futures) { // Throws an exception if an exception was thrown by the task. resultList.add(future.get()); }//from w w w. j a va2 s . c o m long last = (System.currentTimeMillis() - start); // make sure that there are at least one element in resultList is :513 Assert.assertTrue(resultList.contains(":513")); System.out.println("resultList = " + resultList + " response time = " + last); }
From source file:no.dusken.aranea.web.spring.ChainedController.java
/** * Spawns multiple threads, one for each controller in the list of * controllers, and within each thread, delegates to the controller's * handleRequest() method. Once all the threads are complete, the * ModelAndView objects returned from each of the handleRequest() methods * are merged into a single view. The view name for the model is set to the * specified view name. If an exception is thrown by any of the controllers * in the chain, this exception is propagated up from the handleRequest() * method of the ChainedController.// w ww .j a va 2s . c o m * * @param request the HttpServletRequest object. * @param response the HttpServletResponse object. * @return a merged ModelAndView object. * @throws Exception if one is thrown from the controllers in the chain. */ @SuppressWarnings("unchecked") private ModelAndView handleRequestParallely(HttpServletRequest request, HttpServletResponse response) throws Exception { ExecutorService service = Executors.newCachedThreadPool(); int numberOfControllers = controllers.size(); CallableController[] callables = new CallableController[numberOfControllers]; Future<ModelAndView>[] futures = new Future[numberOfControllers]; for (int i = 0; i < numberOfControllers; i++) { callables[i] = new CallableController(controllers.get(i), request, response); futures[i] = service.submit(callables[i]); } ModelAndView mergedModel = new ModelAndView(); for (Future<ModelAndView> future : futures) { ModelAndView model = future.get(); if (model != null) { mergedModel.addAllObjects(model.getModel()); } } if (StringUtils.isNotEmpty(this.viewName)) { mergedModel.setViewName(this.viewName); } return mergedModel; }
From source file:com.amazonaws.services.kinesis.multilang.MessageReaderTest.java
@Test public void readLineFails() throws IOException { BufferedReader input = Mockito.mock(BufferedReader.class); Mockito.doThrow(IOException.class).when(input).readLine(); MessageReader reader = new MessageReader().initialize(input, shardId, new ObjectMapper(), Executors.newCachedThreadPool()); Future<Message> readTask = reader.getNextMessageFromSTDOUT(); try {//from w w w . j a v a 2s. c o m readTask.get(); Assert.fail("The reading task should have failed due to an IOException."); } catch (InterruptedException e) { Assert.fail( "The reading task should not have been interrupted. It should have failed due to an IOException."); } catch (ExecutionException e) { // Yay!! } }
From source file:com.cloudera.oryx.kmeans.computation.local.WeightedPointsByFold.java
@Override public List<List<WeightedRealVector>> call() throws InterruptedException, ExecutionException { Config config = ConfigUtils.getDefaultConfig(); ClusterSettings cluster = ClusterSettings.create(config); KSketchIndex index = buildIndex(foldVecs, cluster); int pointsPerIteration = cluster.getSketchPoints(); RandomGenerator random = RandomManager.getRandom(); ListeningExecutorService exec = MoreExecutors .listeningDecorator(Executors.newFixedThreadPool(config.getInt("model.parallelism"), new ThreadFactoryBuilder().setNameFormat("KSKETCH-%d").setDaemon(true).build())); for (int iter = 0; iter < cluster.getSketchIterations(); iter++) { log.info("Starting sketch iteration {}", iter + 1); List<ListenableFuture<Collection<RealVector>>> futures = Lists.newArrayList(); for (int foldId = 0; foldId < foldVecs.size(); foldId++) { futures.add(exec/* w w w. j av a 2 s.c o m*/ .submit(new SamplingRun(index, random, foldId, foldVecs.get(foldId), pointsPerIteration))); } // At the end of each iteration, gather up the sampled points to add to the index Future<List<Collection<RealVector>>> all = Futures.allAsList(futures); try { List<Collection<RealVector>> newSamples = all.get(); for (int foldId = 0; foldId < foldVecs.size(); foldId++) { for (RealVector v : newSamples.get(foldId)) { index.add(v, foldId); } } } catch (ExecutionException e) { ExecutorUtils.shutdownNowAndAwait(exec); all.cancel(true); throw e; } index.rebuildIndices(); } List<ListenableFuture<List<WeightedRealVector>>> ret = Lists.newArrayList(); for (int foldId = 0; foldId < foldVecs.size(); foldId++) { ret.add(exec.submit(new AssignmentRun(index, foldId, foldVecs.get(foldId)))); } try { return Futures.allAsList(ret).get(); } finally { ExecutorUtils.shutdownNowAndAwait(exec); } }
From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java
@Test public void testBasic() throws Exception { final Timing timing = new Timing(); final List<Closeable> closeables = Lists.newArrayList(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {//from w ww .ja va2s . c om closeables.add(client); client.start(); final CountDownLatch postEnterLatch = new CountDownLatch(QTY); final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); final AtomicInteger count = new AtomicInteger(0); final AtomicInteger max = new AtomicInteger(0); List<Future<Void>> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < QTY; ++i) { Future<Void> future = service.submit(new Callable<Void>() { @Override public Void call() throws Exception { DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); synchronized (TestDistributedDoubleBarrier.this) { int thisCount = count.incrementAndGet(); if (thisCount > max.get()) { max.set(thisCount); } } postEnterLatch.countDown(); Assert.assertTrue(timing.awaitLatch(postEnterLatch)); Assert.assertEquals(count.get(), QTY); Assert.assertTrue(barrier.leave(10, TimeUnit.SECONDS)); count.decrementAndGet(); postLeaveLatch.countDown(); Assert.assertTrue(timing.awaitLatch(postLeaveLatch)); return null; } }); futures.add(future); } for (Future<Void> f : futures) { f.get(); } Assert.assertEquals(count.get(), 0); Assert.assertEquals(max.get(), QTY); } finally { for (Closeable c : closeables) { IOUtils.closeQuietly(c); } } }
From source file:org.jasig.cas.ticket.registry.JpaTicketRegistryTests.java
@Test @IfProfileValue(name = "cas.jpa.concurrent", value = "true") public void testConcurrentServiceTicketGeneration() throws Exception { final TicketGrantingTicket newTgt = newTGT(); addTicketInTransaction(newTgt);/*from ww w.jav a2s . com*/ final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE); try { final List<ServiceTicketGenerator> generators = new ArrayList<ServiceTicketGenerator>(CONCURRENT_SIZE); for (int i = 0; i < CONCURRENT_SIZE; i++) { generators.add(new ServiceTicketGenerator(newTgt.getId())); } final List<Future<String>> results = executor.invokeAll(generators); for (Future<String> result : results) { assertNotNull(result.get()); } } catch (Exception e) { logger.debug("testConcurrentServiceTicketGeneration produced an error", e); fail("testConcurrentServiceTicketGeneration failed."); } finally { executor.shutdownNow(); } }
From source file:com.opengamma.integration.viewer.status.impl.ViewStatusCalculationWorker.java
public ViewStatusResultAggregator run() { ViewStatusResultAggregator aggregator = new ViewStatusResultAggregatorImpl(); CompletionService<PerViewStatusResult> completionService = new ExecutorCompletionService<PerViewStatusResult>( _executor);//from w w w. j a va2 s . c om //submit task to executor to run partitioned by security type for (String securityType : _valueRequirementBySecType.keySet()) { Collection<String> valueRequirements = _valueRequirementBySecType.get(securityType); completionService.submit(new ViewStatusCalculationTask(_toolContext, _portfolioId, _user, securityType, valueRequirements, _marketDataSpecification)); } try { // process all completed task for (int i = 0; i < _valueRequirementBySecType.size(); i++) { Future<PerViewStatusResult> futureTask = completionService.take(); PerViewStatusResult perViewStatusResult = futureTask.get(); for (ViewStatusKey viewStatusKey : perViewStatusResult.keySet()) { aggregator.putStatus(viewStatusKey, perViewStatusResult.get(viewStatusKey)); } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (ExecutionException ex) { throw new OpenGammaRuntimeException("Error running View status report", ex.getCause()); } return aggregator; }
From source file:com.tascape.qa.th.SuiteRunner.java
public int startExecution() throws IOException, InterruptedException, SQLException, XMLStreamException { File dir = SYS_CONFIG.getLogPath().resolve(execId).toFile(); LOG.info("Create suite execution log directory {}", dir); if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Cannot create directory " + dir); }/*from w w w . ja v a2s.c om*/ this.logAppProperties(dir); int threadCount = SYS_CONFIG.getExecutionThreadCount(); LOG.info("Start execution engine with {} thread(s)", threadCount); int len = (threadCount + "").length(); ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("t%0" + len + "d").build(); ExecutorService executorService = Executors.newFixedThreadPool(threadCount, namedThreadFactory); CompletionService<TestResult> completionService = new ExecutorCompletionService<>(executorService); LOG.info("Start to acquire test cases to execute"); int numberOfFailures = 0; try { List<TestResult> tcrs = this.filter(this.db.getQueuedTestCaseResults(this.execId, 100)); while (!tcrs.isEmpty()) { List<Future<TestResult>> futures = new ArrayList<>(); for (TestResult tcr : tcrs) { LOG.info("Submit test case {}", tcr.getTestCase().format()); futures.add(completionService.submit(new TestRunnerJUnit4(db, tcr))); } LOG.debug("Total {} test cases submitted", futures.size()); for (Future<TestResult> f : futures) { try { Future<TestResult> future = completionService.take(); TestResult tcr = future.get(); if (tcr == null) { continue; } String result = tcr.getResult().result(); LOG.info("Get result of test case {} - {}", tcr.getTestCase().format(), result); if (!ExecutionResult.PASS.name().equals(result) && !result.endsWith("/0")) { numberOfFailures++; } } catch (Throwable ex) { LOG.error("Error executing test thread", ex); numberOfFailures++; } } tcrs = this.filter(this.db.getQueuedTestCaseResults(this.execId, 100)); } } finally { AbstractSuite.getSuites().stream().forEach((suite) -> { try { suite.tearDown(); } catch (Exception ex) { LOG.warn("Error tearing down suite {} - {}", suite.getClass(), ex.getMessage()); } }); } executorService.shutdown(); LOG.info("No more test case to run on this host, updating suite execution result"); this.db.updateSuiteExecutionResult(this.execId); this.db.saveJunitXml(this.execId); return numberOfFailures; }
From source file:com.crossbusiness.resiliency.aspect.AnnotationAsyncAspectTest.java
@Test public void qualified_async_methods_are_routed_to_correct_executor() throws InterruptedException, ExecutionException { ClassWithQualifiedAsyncMethods obj = new ClassWithQualifiedAsyncMethods(); Future<Thread> sumoThread = obj.sumoThreadPoolWork(); assertThat(sumoThread.get(), not(Thread.currentThread())); assertThat(sumoThread.get().getName(), startsWith("sumoThreadPool")); Future<Thread> twoPoolThread = obj.twoThreadPoolWork(); assertThat(twoPoolThread.get().getName(), startsWith("twoThreadPool")); }