List of usage examples for java.util.concurrent Future get
V get() throws InterruptedException, ExecutionException;
From source file:org.jolokia.client.request.J4pConnectionPoolingIntegrationTest.java
private void searchParallel(J4pClient j4pClient) throws Exception { stubFor(get(urlPathMatching("/test/([a-z]*)")) .willReturn(aResponse().withFixedDelay(1000).withBody(getJsonResponse("test")))); final ExecutorService executorService = Executors.newFixedThreadPool(20); final J4pSearchRequest j4pSearchRequest = new J4pSearchRequest("java.lang:type=*"); final List<Future<Void>> requestsList = new ArrayList<Future<Void>>(); for (int i = 0; i < 20; i++) { requestsList.add(executorService.submit(new AsyncRequest(j4pClient, j4pSearchRequest))); }//from w ww . j av a 2s . c o m for (Future<Void> requests : requestsList) { requests.get(); } executorService.shutdown(); }
From source file:com.migo.utils.ScheduleJob.java
@Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { ScheduleJobEntity scheduleJob = (ScheduleJobEntity) jobExecutionContext.getMergedJobDataMap() .get(ScheduleJobEntity.JOB_PARAM_KEY); //?spring bean ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils .getBean("scheduleJobLogService"); //??//www . j a v a2 s .c o m ScheduleJobLogEntity log = new ScheduleJobLogEntity(); log.setJobId(scheduleJob.getJobId()); log.setBeanName(scheduleJob.getBeanName()); log.setMethodName(scheduleJob.getMethodName()); log.setParams(scheduleJob.getParams()); log.setCreateTime(new Date()); // long startTime = System.currentTimeMillis(); try { // logger.info("ID" + scheduleJob.getJobId()); ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams()); Future<?> future = service.submit(task); future.get(); // long times = System.currentTimeMillis() - startTime; log.setTimes((int) times); //? 0? 1 log.setStatus(0); logger.info("ID" + scheduleJob.getJobId() + " " + times + ""); } catch (Exception e) { logger.error("ID" + scheduleJob.getJobId(), e); // long times = System.currentTimeMillis() - startTime; log.setTimes((int) times); //? 0? 1 log.setStatus(1); log.setError(StringUtils.substring(e.toString(), 0, 2000)); } finally { scheduleJobLogService.save(log); } }
From source file:eu.cloudscale.showcase.servlets.helpers.PaymentService.java
@Async public Future<String> callPaymentService(String distribution, String attr1, String attr2, String attr3) { try {// w w w.j a va2 s.co m ExecutorService executor = Executors.newFixedThreadPool(1); String url = this.getUrl(distribution, attr1, attr2, attr3); Future<Response> response = executor.submit(new Request(new URL(url))); InputStream input = response.get().getBody(); executor.shutdown(); String body = IOUtils.toString(input, "UTF-8"); return new AsyncResult<String>(body); } catch (MalformedURLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.espertech.esper.multithread.TestMTContextListenerDispatch.java
private void tryPerformanceDispatch(int numThreads, int numRepeats) throws Exception { MyListener listener = new MyListener(); engine.getEPAdministrator().getStatement("select").addListener(listener); List<Object>[] events = new ArrayList[numThreads]; int eventId = 0; for (int threadNum = 0; threadNum < numThreads; threadNum++) { events[threadNum] = new ArrayList<Object>(); for (int eventNum = 0; eventNum < numRepeats; eventNum++) { // range: 1 to 1000 int partition = (int) (Math.random() * 50); eventId++;//from w w w .jav a 2 s. co m events[threadNum].add(new SupportBean(new Integer(partition).toString(), eventId)); } } ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); Future futures[] = new Future[numThreads]; long startTime = System.currentTimeMillis(); for (int i = 0; i < numThreads; i++) { Callable callable = new SendEventCallable(i, engine, events[i].iterator()); futures[i] = threadPool.submit(callable); } for (Future future : futures) { assertEquals(true, future.get()); } long delta = System.currentTimeMillis() - startTime; threadPool.shutdown(); threadPool.awaitTermination(10, TimeUnit.SECONDS); // print those events not received for (List<Object> eventList : events) { for (Object event : eventList) { if (!listener.getBeans().contains(event)) { log.info("Expected event was not received, event " + event); } } } assertEquals(numRepeats * numThreads, listener.getBeans().size()); assertTrue("delta=" + delta, delta < 500); }
From source file:com.chingo247.structureapi.plan.document.PlanDocumentManager.java
/** * Loads all planDocuments & structureDocuments Multi-Core. Number of cores used is defined by * the number of cores available using Runtime.getRuntime.availableProcessors() *//*from w w w . j a v a 2 s .com*/ @Override public synchronized void loadDocuments() { // Go throug all XML files inside the 'Plans' folder Iterator<File> it = FileUtils.iterateFiles(structureAPI.getPlanDataFolder(), new String[] { "xml" }, true); final List<Future> tasks = new LinkedList<>(); while (it.hasNext()) { final File planDocFile = it.next(); tasks.add(executor.submit(new Runnable() { @Override public void run() { try { SAXReader reader = new SAXReader(); Document d = reader.read(planDocFile); // If the RootElement is not 'StructurePlan', skip it if (!isStructurePlan(d)) { return; } List<Element> elements = d.getRootElement().elements(); // Form plan document PlanDocument planDocument = new PlanDocument(PlanDocumentManager.this, planDocFile); for (Element pluginElement : elements) { planDocument.putPluginElement(pluginElement.getName(), new PlanDocumentPluginElement( pluginElement.getName(), planDocument, pluginElement)); } // Save the document PlanDocumentManager.this.put(planDocument.getRelativePath(), planDocument); } catch (DocumentException ex) { Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex); } } })); } // Block until all tasks are done for (Future f : tasks) { try { f.get(); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex); for (Future fu : tasks) { fu.cancel(true); } } } }
From source file:io.undertow.servlet.test.request.ExecutorPerServletTestCase.java
public int runTest(final String path) throws IOException, ExecutionException, InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS); try {/*ww w . j a v a 2s . c om*/ final List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < NUM_THREADS; ++i) { futures.add(executor.submit(new Runnable() { @Override public void run() { TestHttpClient client = new TestHttpClient(); try { for (int i = 0; i < NUM_REQUESTS; ++i) { HttpGet get = new HttpGet( DefaultServer.getDefaultServerURL() + "/servletContext" + path); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); final String response = HttpClientUtils.readResponse(result); } } catch (IOException e) { throw new RuntimeException(e); } finally { client.getConnectionManager().shutdown(); } } })); } for (Future<?> future : futures) { future.get(); } TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext" + path); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); return Integer.parseInt(HttpClientUtils.readResponse(result)); } finally { client.getConnectionManager().shutdown(); } } finally { executor.shutdown(); } }
From source file:de.tbuchloh.kiskis.cracker.PasswordCracker.java
public String crackPassword() { final Long totalEstimation = _passwordCreator.estimateTotalCount(); _progressListener.notifyTotalCount(totalEstimation); _progressListener.notifyStartTime(System.currentTimeMillis()); final AtomicBoolean found = new AtomicBoolean(false); final Callable<String> callable = new Callable<String>() { @Override// ww w . ja v a2s .co m public String call() throws Exception { String guess; while (!found.get() && (guess = _passwordCreator.create()) != null) { _progressListener.notifyTry(guess); if (_tester.test(guess)) { found.set(true); return guess; } } return null; } }; final int cpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors(); LOG.info(String.format("Found %1$d cpus ...", cpus)); final ExecutorService threadPool = Executors.newFixedThreadPool(cpus); final Collection<Callable<String>> tasks = new ArrayList<Callable<String>>(); for (int i = 0; i < cpus; ++i) { tasks.add(callable); } try { final List<Future<String>> futures = threadPool.invokeAll(tasks); for (final Future<String> future : futures) { final String guessedPwd = future.get(); if (guessedPwd != null) { return guessedPwd; } } return null; } catch (final InterruptedException e) { throw new KisKisRuntimeException("InterruptedException", e); } catch (final ExecutionException e) { throw new KisKisRuntimeException("ExecutionException", e); } }
From source file:com.netflix.hollow.jsonadapter.AbstractHollowJsonAdaptorTask.java
protected boolean wait(List<Future<?>> futureList) throws Exception { boolean isSuccess = false; for (final Future<?> f : futureList) { try {//www.ja v a2 s .c o m f.get(); isSuccess = true; } catch (final InterruptedException e) { e.printStackTrace(); } catch (final ExecutionException e) { e.printStackTrace(); throw e; } } return isSuccess; }
From source file:com.newlandframework.avatarmq.core.AckMessageCache.java
public void parallelDispatch(LinkedList<String> list) { List<Callable<Long>> tasks = new ArrayList<Callable<Long>>(); List<Future<Long>> futureList = new ArrayList<Future<Long>>(); int startPosition = 0; Pair<Integer, Integer> pair = calculateBlocks(list.size(), list.size()); int numberOfThreads = pair.getRight(); int blocks = pair.getLeft(); barrier = new CyclicBarrier(numberOfThreads); for (int i = 0; i < numberOfThreads; i++) { String[] task = new String[blocks]; System.arraycopy(list.toArray(), startPosition, task, 0, blocks); tasks.add(new AckMessageTask(barrier, task)); startPosition += blocks;/*w w w. ja v a2 s.com*/ } ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); try { futureList = executor.invokeAll(tasks); } catch (InterruptedException ex) { Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex); } for (Future<Long> longFuture : futureList) { try { succTaskCount += longFuture.get(); } catch (InterruptedException ex) { Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:org.auraframework.integration.test.http.AuraResourceServletLoggingHttpTest.java
/** * test add for W-2792895// w w w. j a v a 2 s. c o m also since I ask cache to log something when hit miss, this kind of verify W-2105858 as well */ @Test public void testConcurrentGetRequests() throws Exception { // I tried to use obtainGetMethod(url) then perform(HttpGet) , but // our default httpClient use BasicClientConnectionManager, which doesn't work well with MultiThread // let's use PoolingHttpClientConnectionManager instead. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // Increase max total connection to 200 -- just some big number cm.setMaxTotal(200); // Increase default max connection per route to 20 -- again, just some big numer cm.setDefaultMaxPerRoute(20); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); String modeAndContext = getSimpleContext(Format.JS, false); String url = "/l/" + AuraTextUtil.urlencode(modeAndContext) + "/app.js"; int numOfRequest = 5; List<Request> requests = new ArrayList<>(); for (int i = 1; i <= numOfRequest; i++) { requests.add(new Request(httpClient, url)); } ExecutorService excutor = Executors.newFixedThreadPool(numOfRequest); List<Future<Integer>> responses = new ArrayList<>(); for (Request request : requests) { responses.add(excutor.submit(request)); } for (Future<Integer> response : responses) { response.get(); } int counter = 0; String message; List<LoggingEvent> logs = appender.getLog(); for (LoggingEvent le : logs) { message = le.getMessage().toString(); if (message.contains("StringsCache")) { counter++; assertTrue("get unexpected logging message for cache miss:" + message, message.contains("cache miss for key: JS:DEV:")); } } //run this test right after server is up, we get one miss. second time, what we looking for is cached already, no miss. assertTrue("we should only have no more than one cache miss, instead we have " + counter, counter <= 1); }