List of usage examples for java.util.concurrent Future get
V get() throws InterruptedException, ExecutionException;
From source file:FutureTest.java
public Integer call() { count = 0;/*from www. j a va 2 s . c om*/ try { File[] files = directory.listFiles(); ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>(); for (File file : files) if (file.isDirectory()) { MatchCounter counter = new MatchCounter(file, keyword); FutureTask<Integer> task = new FutureTask<Integer>(counter); results.add(task); Thread t = new Thread(task); t.start(); } else { if (search(file)) count++; } for (Future<Integer> result : results) try { count += result.get(); } catch (ExecutionException e) { e.printStackTrace(); } } catch (InterruptedException e) { } return count; }
From source file:com.mycompany.asyncreq.GetThread.java
@Override public void run() { try {/*from w w w . j a va 2s. co m*/ Future<HttpResponse> future = client.execute(request, context, null); HttpResponse response = future.get(); MatcherAssert.assertThat(response.getStatusLine().getReasonPhrase(), equals(200)); Boolean isDone = true; Scanner scan = new Scanner(System.in); File f = new File("my.txt"); FileWriter fr = new FileWriter(f); BufferedWriter bwr = new BufferedWriter(fr); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); while ((br.readLine()) != null) { bwr.write(new Scanner(System.in).nextLine()); } } catch (Exception ex) { System.out.println(ex.getLocalizedMessage()); } }
From source file:com.asakusafw.runtime.directio.hadoop.HadoopDataSourceUtil.java
private static void parallel(ExecutorService executor, Collection<? extends Callable<?>> tasks) throws IOException, InterruptedException { List<Future<?>> futures = tasks.stream().map(task -> executor.submit(task)).collect(Collectors.toList()); for (Future<?> future : futures) { try {// www. java 2 s .com future.get(); } catch (CancellationException | InterruptedException e) { cancel(futures); throw e; } catch (ExecutionException e) { cancel(futures); try { throw e.getCause(); } catch (Error | RuntimeException | IOException | InterruptedException cause) { throw cause; } catch (Throwable cause) { throw new IOException(cause); } } } }
From source file:com.googlecode.jcasockets.perf.Client.java
public void execute() throws InterruptedException, ExecutionException { int numberOfThreads = clientOptions.getNumberOfThreads(); String ipAddress = clientOptions.getIpAddress(); List<Integer> ports = clientOptions.getPorts(); ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); try {/*from www . j a v a 2 s . c om*/ Collection<Callable<ExecutionStatistics>> senderTestRunners = new ArrayList<Callable<ExecutionStatistics>>( numberOfThreads); for (Integer port : ports) { for (int i = 0; i < numberOfThreads; i++) { SocketSender socketSender = socketSenderFactory.createSocketSender(ipAddress, port); senderTestRunners.add(new SenderTestRunner(clientOptions, socketSender)); } } List<Future<ExecutionStatistics>> executionStatisticsFutures = executorService .invokeAll(senderTestRunners); executionStatistics = new ExecutionStatistics(null); for (Future<ExecutionStatistics> future : executionStatisticsFutures) { ExecutionStatistics that = future.get(); executionStatistics.combine(that); } } finally { executorService.shutdown(); } }
From source file:io.undertow.server.handlers.file.FileHandlerStressTestCase.java
@Test public void simpleFileStressTest() throws IOException, ExecutionException, InterruptedException, URISyntaxException { ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS); try {//from ww w . ja v a 2 s. c o m Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent(); final ResourceHandler handler = new ResourceHandler(new PathResourceManager(rootPath, 10485760)); final CacheHandler cacheHandler = new CacheHandler(new DirectBufferCache(1024, 10, 10480), handler); final PathHandler path = new PathHandler(); path.addPrefixPath("/path", cacheHandler); final CanonicalPathHandler root = new CanonicalPathHandler(); root.setNext(path); DefaultServer.setRootHandler(root); 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() + "/path/page.html"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); final String response = HttpClientUtils.readResponse(result); Assert.assertTrue(response, response.contains("A web page")); } } catch (IOException e) { throw new RuntimeException(e); } finally { client.getConnectionManager().shutdown(); } } })); } for (Future<?> future : futures) { future.get(); } } finally { executor.shutdown(); } }
From source file:com.ning.metrics.goodwill.access.GoodwillAccessorTest.java
@Test(enabled = false, groups = "slow") public void testIntegration() throws Exception { GoodwillAccessor accessor = new GoodwillAccessor("localhost", 8080); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); Future<List<GoodwillSchema>> thrifts = accessor.getSchemata(); List<GoodwillSchema> schemata = thrifts.get(); // Simple test to make sure we got actual GoodwillSchema, 0.0.5 has the following bug: // java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.ning.metrics.goodwill.access.GoodwillSchema Assert.assertTrue(schemata.get(0).getName().length() > 0); System.out.println(String.format("All thrifts:\n%s", mapper.writeValueAsString(schemata))); Future<GoodwillSchema> thrift = accessor.getSchema("Awesomeness"); GoodwillSchema schema = thrift.get(); Assert.assertTrue(schema.getName().length() > 0); System.out.println(String.format("Awesomeness thrift:\n%s", mapper.writeValueAsString(schema))); accessor.close();/*from ww w. j a v a 2s. co m*/ }
From source file:org.apache.camel.component.http4.HttpConcurrentTest.java
private void doSendMessages(int files, int poolSize) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(poolSize); // we access the responses Map below only inside the main thread, // so no need for a thread-safe Map implementation Map<Integer, Future<String>> responses = new HashMap<Integer, Future<String>>(); for (int i = 0; i < files; i++) { final int index = i; Future<String> out = executor.submit(new Callable<String>() { public String call() throws Exception { return template.requestBody("http4://" + getHostName() + ":" + getPort(), null, String.class); }/*w w w. ja v a 2s . c o m*/ }); responses.put(index, out); } assertEquals(files, responses.size()); // get all responses Set<String> unique = new HashSet<String>(); for (Future<String> future : responses.values()) { unique.add(future.get()); } // should be 'files' unique responses assertEquals("Should be " + files + " unique responses", files, unique.size()); executor.shutdownNow(); }
From source file:com.developmentsprint.spring.breaker.hystrix.HystrixAnnotationDrivenConcreteClassTest.java
@Test public void testMaxConcurrency() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(20); List<Future<String>> futures = new ArrayList<Future<String>>(); for (int i = 0; i < 20; i++) { futures.add(executor.submit(new Callable<String>() { @Override/*w w w. j ava 2 s . c o m*/ public String call() throws Exception { return methods.getText(); } })); } Thread.sleep(500L); int successes = 0; int rejections = 0; for (Future<String> future : futures) { try { future.get(); successes++; } catch (Exception e) { rejections++; } } assertThat(successes).isEqualTo(10); assertThat(rejections).isEqualTo(10); }
From source file:com.flipkart.bifrost.SampleUsageTest.java
@Test public void testSendReceive() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); Connection connection = new Connection(Lists.newArrayList("localhost"), "guest", "guest"); connection.start();// www . j a va 2 s . c o m //Create executor BifrostExecutor<Map<String, Object>> executor = BifrostExecutor .<Map<String, Object>>builder(HttpCallCommand.class).connection(connection).objectMapper(mapper) .requestQueue("bifrost-send").responseQueue("bifrost-recv") .executorService(Executors.newFixedThreadPool(10)).responseWaitTimeout(20000).build(); //Create execution server BifrostRemoteCallExecutionServer<Map<String, Object>> executionServer = BifrostRemoteCallExecutionServer .<Map<String, Object>>builder(HttpCallCommand.class).objectMapper(mapper).connection(connection) .concurrency(10).requestQueue("bifrost-send").build(); executionServer.start(); //Start making calls RemoteCallable<Map<String, Object>> callable = HttpCallCommand.createGet("http://jsonip.com/"); Future<Map<String, Object>> result = executor.submit(callable); Map<String, Object> r = result.get(); //Shutdown exverything when done executor.shutdown(); executionServer.stop(); connection.stop(); Assert.assertTrue(r.containsKey("ip")); }
From source file:io.renren.modules.job.utils.ScheduleJob.java
@Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap() .get(ScheduleJobEntity.JOB_PARAM_KEY); //?spring bean ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils .getBean("scheduleJobLogService"); //??/*from w w w.j av a 2s . c om*/ 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.insert(log); } }