List of usage examples for java.util.concurrent Future get
V get() throws InterruptedException, ExecutionException;
From source file:com.thoughtworks.go.server.security.LdapAuthenticationTest.java
@Test public void shouldAuthenticateConcurrently() throws Exception { ldapServer.addUser(employeesOrgUnit, "foleys", "some-password", "Shilpa Foley", "foleys@somecompany.com"); ExecutorService pool = Executors.newFixedThreadPool(100); List<Callable<String>> allCallables = new ArrayList<Callable<String>>(); for (int i = 0; i < 100; i++) { final boolean even = i % 2 == 0; allCallables.add(new Callable<String>() { @Override//w w w . j a v a 2 s . co m public String call() throws Exception { if (even) { assertAuthenticationOfValidAdminUser("foleys", "some-password"); } else { assertFailedAuthentication("invalid_user", ""); } return ""; } }); } List<Future<String>> futures = pool.invokeAll(allCallables); pool.shutdown(); boolean finishedWithoutTimeout = pool.awaitTermination(10, TimeUnit.SECONDS); assertThat(finishedWithoutTimeout, is(true)); // Assert no exceptions, by getting result. for (Future<String> future : futures) { future.get(); } }
From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java
private void fillResultListWithFutureResults(List<Future<Object>> futures, List<Object> resultList) { for (Future<Object> future : futures) { try {//from w w w . ja v a 2s. c o m resultList.add(future.get()); } catch (InterruptedException e) { throw new ConcurrencyFailureException( "interrupted when processing data access request in concurrency", e); } catch (ExecutionException e) { throw new ConcurrencyFailureException("something goes wrong in processing", e); } } }
From source file:io.ecarf.core.cloud.task.processor.files.ProcessFilesTask.java
@Override public void run() throws IOException { log.info("START: processing files"); Stopwatch stopwatch = Stopwatch.createStarted(); Set<String> filesSet = ObjectUtils.csvToSet(files); log.info("Processing files: " + filesSet); List<Callable<T>> tasks = getSubTasks(filesSet); int processors = Runtime.getRuntime().availableProcessors(); try {/*ww w. j a va 2 s.c o m*/ // check if we only have one file to process if (tasks.size() == 1) { this.processSingleOutput(tasks.get(0).call()); } else if (processors == 1) { // only one process then process synchronously List<T> output = new ArrayList<>(); for (Callable<T> task : tasks) { output.add(task.call()); } this.processMultiOutput(output); } else { // multiple cores ExecutorService executor = Utils.createFixedThreadPool(processors); try { List<Future<T>> results = executor.invokeAll(tasks); List<T> output = new ArrayList<>(); for (Future<T> result : results) { output.add(result.get()); } this.processMultiOutput(output); } finally { executor.shutdown(); } } } catch (Exception e) { log.error("Failed to process multiple files", e); throw new IOException(e); } log.info("TIMER# All files are processed successfully, elapsed time: " + stopwatch); }
From source file:org.fcrepo.kernel.modeshape.spring.ModeShapeRepositoryFactoryBean.java
/** * Attempts to undeploy the repository and shutdown the ModeShape engine on * context destroy./*from w w w . jav a 2 s. c om*/ * * @throws InterruptedException if interrupted exception occurred */ @PreDestroy public void stopRepository() throws InterruptedException { LOGGER.info("Initiating shutdown of ModeShape"); final String repoName = repository.getName(); try { final Future<Boolean> futureUndeployRepo = modeShapeEngine.undeploy(repoName); if (futureUndeployRepo.get()) { LOGGER.info("ModeShape repository {} has undeployed.", repoName); } else { LOGGER.error("ModeShape repository {} undeploy failed without an exception, still deployed.", repoName); } LOGGER.info("Repository {} undeployed.", repoName); } catch (final NoSuchRepositoryException e) { LOGGER.error("Repository {} unknown, cannot undeploy.", repoName, e); } catch (final ExecutionException e) { LOGGER.error("Repository {} cannot undeploy.", repoName, e.getCause()); } final Future<Boolean> futureShutdownEngine = modeShapeEngine.shutdown(); try { if (futureShutdownEngine.get()) { LOGGER.info("ModeShape Engine has shutdown."); } else { LOGGER.error("ModeShape Engine shutdown failed without an exception, still running."); } } catch (final ExecutionException e) { LOGGER.error("ModeShape Engine shutdown failed.", e.getCause()); } }
From source file:com.laudandjolynn.mytv.proxy.MyTvProxyManager.java
public void prepareProxies(ProxyProvider... providers) { int length = providers == null ? 0 : providers.length; if (length > 0) { int maxThreadNum = Constant.CPU_PROCESSOR_NUM; ThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("MyTv_Find_Proxies_%d") .build();//from ww w . j a va2 s . c om ExecutorService executorService = Executors .newFixedThreadPool(length > maxThreadNum ? maxThreadNum : length, threadFactory); CompletionService<List<Proxy>> completionService = new ExecutorCompletionService<List<Proxy>>( executorService); providerList.clear(); for (int i = 0; i < length; i++) { final ProxyProvider provider = providers[i]; providerList.add(provider); completionService.submit(new Callable<List<Proxy>>() { @Override public List<Proxy> call() throws Exception { return provider.getProxies(); } }); } executorService.shutdown(); int count = 0; List<Proxy> resultList = new ArrayList<Proxy>(); while (count < length) { try { Future<List<Proxy>> future = completionService.take(); List<Proxy> proxies = future.get(); if (proxies != null) { resultList.addAll(proxies); } } catch (InterruptedException e) { logger.error("get proxies thread has interrupted.", e); } catch (ExecutionException e) { logger.error("get proxies thread has execution fail.", e); } count++; } resultList.add(LOCALHOST_PROXY); PROXY_QUEUE.clear(); PROXY_QUEUE.addAll(resultList); } }
From source file:de.zib.gndms.infra.system.DummyTaskActionTest.java
private void postInterruption(final @NotNull String pk) throws ResourceException, InterruptedException, ExecutionException { runDatabase();// w w w . ja va 2 s . co m final EntityManager newEM = getSys().getEntityManagerFactory().createEntityManager(); final DummyTaskAction action = new DummyTaskAction(newEM, pk); action.setSuccessRate(1.0d); final Future<AbstractTask> continuedFuture = getSys().submitAction(action, log); assert continuedFuture.get().getState().equals(TaskState.FINISHED); shutdownDatabase(); }
From source file:org.createnet.raptor.indexer.impl.es.ElasticSearchIndexAdmin.java
public void delete(String name) { DeleteIndexRequest deleteIndexReq = new DeleteIndexRequest(name); Future<DeleteIndexResponse> reqCreate = client.admin().indices().delete(deleteIndexReq); try {//from w w w. ja v a 2 s. c o m DeleteIndexResponse resDelete = reqCreate.get(); } catch (InterruptedException | ExecutionException ex) { throw new IndexAdminException(ex); } logger.debug("Delete index {}", name); }
From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedBarrier.java
@Test public void testMultiClient() throws Exception { CuratorFramework client1 = null;/*w w w . java 2s . co m*/ CuratorFramework client2 = null; try { { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); } finally { IOUtils.closeQuietly(client); } } client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); List<Future<Object>> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); for (final CuratorFramework c : new CuratorFramework[] { client1, client2 }) { Future<Object> future = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { c.start(); DistributedBarrier barrier = new DistributedBarrier(c, "/barrier"); barrier.waitOnBarrier(10, TimeUnit.MILLISECONDS); return null; } }); futures.add(future); } Thread.sleep(1000); { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.removeBarrier(); } finally { IOUtils.closeQuietly(client); } } for (Future<Object> f : futures) { f.get(); } } finally { IOUtils.closeQuietly(client1); IOUtils.closeQuietly(client2); } }
From source file:com.aerofs.baseline.json.TestJSONHandling.java
@Test public void shouldReceiveErrorOnMakingPostWithInvalidJsonObject() throws ExecutionException, InterruptedException, JsonProcessingException { // noinspection ConstantConditions String serialized = mapper.writeValueAsString(new JsonObject(null, "allen")); // yes; I know I'm using 'null' ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII)); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(contentInputStream); HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer"); post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)); post.setEntity(entity);/* w w w . j a va 2 s. com*/ Future<HttpResponse> future = client.getClient().execute(post, null); HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_BAD_REQUEST)); }
From source file:com.ok2c.lightmtp.impl.protocol.PipeliningReceiveEnvelopCodec.java
private SMTPReply getReply(final Future<SMTPReply> future) { try {/* ww w.ja va 2 s . c o m*/ return future.get(); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } return new SMTPReply(SMTPCodes.ERR_PERM_TRX_FAILED, new SMTPCode(5, 3, 0), cause.getMessage()); } catch (InterruptedException ex) { return new SMTPReply(SMTPCodes.ERR_PERM_TRX_FAILED, new SMTPCode(5, 3, 0), ex.getMessage()); } }