List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:com.google.wave.api.robot.HttpRobotConnection.java
@Override public ListenableFuture<String> asyncPostJson(final String url, final String body) { return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() { @Override/*from w w w . j a v a 2s.co m*/ public String call() throws RobotConnectionException { return postJson(url, body); } })); }
From source file:com.microsoft.azure.management.resources.ResourceProviderOperationDetailsOperationsImpl.java
/** * Gets a list of resource providers./* www .j a v a 2 s. com*/ * * @param identity Required. Resource identity. * @return List of resource provider operations. */ @Override public Future<ResourceProviderOperationDetailListResult> listAsync(final ResourceIdentity identity) { return this.getClient().getExecutorService() .submit(new Callable<ResourceProviderOperationDetailListResult>() { @Override public ResourceProviderOperationDetailListResult call() throws Exception { return list(identity); } }); }
From source file:org.apache.brooklyn.entity.brooklynnode.SelectMasterEffectorTest.java
@BeforeMethod(alwaysRun = true) public void setUp() throws Exception { super.setUp(); // because the effector calls wait for a state change, use a separate thread to drive that poller = new Poller<Void>((EntityLocal) app, false); poller.scheduleAtFixedRate(new Callable<Void>() { @Override/*from w ww.j av a 2s . c o m*/ public Void call() throws Exception { masterFailoverIfNeeded(); return null; } }, new DelegatingPollHandler<Void>(Collections.<AttributePollHandler<? super Void>>emptyList()), Duration.millis(20)); poller.start(); }
From source file:cherry.foundation.mail.SendMailBatchTest.java
@Test public void testMailSendException() throws Exception { final File shutdownTrigger = new File("./shutdownTrigger.txt"); shutdownTrigger.deleteOnExit();// w w w .ja v a2s. com Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() { try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) { return true; } catch (IOException ex) { return false; } } }; ScheduledExecutorService service = Executors.newScheduledThreadPool(1); ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS); SendMailBatch batch = create(1000L, shutdownTrigger, true); ExitStatus status = batch.execute(); assertEquals(ExitStatus.NORMAL, status); assertTrue(future.get().booleanValue()); assertFalse(shutdownTrigger.exists()); verify(bizDateTime, atLeastOnce()).now(); verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L)); verify(mailSendHandler, never()).sendMessage(eq(2L)); verify(mailSendHandler, never()).sendMessage(eq(3L)); }
From source file:aos.camel.JavaFutureTest.java
@Test public void testFutureWithoutDone() throws Exception { // this is the task we want to execute async // usually the task is something that takes // some time to do Callable<String> task = new Callable<String>() { public String call() throws Exception { // do something that takes some time LOG.info("Starting to process task"); Thread.sleep(5000);// w w w. j a v a2 s . c o m LOG.info("Task is now done"); return "Camel rocks"; } }; // this is the thread pool we will use ExecutorService executor = Executors.newCachedThreadPool(); // now submit the task to the thread pool // and get the Future handle back so we can later get the result LOG.info("Submitting task to ExecutorService"); Future<String> future = executor.submit(task); LOG.info("Task submitted and we got a Future handle"); // instead of testing when we are done we can just get // the result and it will automatic wait until the task is done String answer = future.get(); LOG.info("The answer is: " + answer); }
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 w ww . java 2 s .c o m 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:org.apache.brooklyn.entity.brooklynnode.BrooklynEntityMirrorImpl.java
protected void connectSensorsAsync() { Callable<Void> asyncTask = new Callable<Void>() { @Override//from w ww . j av a 2s.c om public Void call() throws Exception { //blocks until available (could be a task) String mirroredEntityUrl = getConfig(MIRRORED_ENTITY_URL); Preconditions.checkNotNull(mirroredEntityUrl, "Required config: " + MIRRORED_ENTITY_URL); connectSensors(mirroredEntityUrl); return null; } }; DynamicTasks .queueIfPossible( Tasks.<Void>builder().displayName("Start entity mirror feed").body(asyncTask).build()) .orSubmitAsync(this); }
From source file:com.ibm.stocator.fs.swift.SwiftOutputStream.java
/** * Default constructor/*from ww w.j a v a 2 s . c o m*/ * * @param account JOSS account object * @param url URL connection * @param contentType content type * @param metadata input metadata * @param connectionManager SwiftConnectionManager * @throws IOException if error */ public SwiftOutputStream(JossAccount account, URL url, final String contentType, Map<String, String> metadata, SwiftConnectionManager connectionManager) throws IOException { mUrl = url; totalWritten = 0; mAccount = account; client = connectionManager.createHttpConnection(); request = new HttpPut(mUrl.toString()); request.addHeader("X-Auth-Token", account.getAuthToken()); if (metadata != null && !metadata.isEmpty()) { for (Map.Entry<String, String> entry : metadata.entrySet()) { request.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue()); } } PipedOutputStream out = new PipedOutputStream(); final PipedInputStream in = new PipedInputStream(); out.connect(in); execService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); mOutputStream = out; Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { InputStreamEntity entity = new InputStreamEntity(in, -1); entity.setChunked(true); entity.setContentType(contentType); request.setEntity(entity); LOG.debug("HTTP PUT request {}", mUrl.toString()); HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); LOG.debug("HTTP PUT response {}. Response code {}", mUrl.toString(), responseCode); if (responseCode == 401) { // Unauthorized error mAccount.authenticate(); request.removeHeaders("X-Auth-Token"); request.addHeader("X-Auth-Token", mAccount.getAuthToken()); LOG.warn("Token recreated for {}. Retry request", mUrl.toString()); response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); } if (responseCode >= 400) { // Code may have changed from retrying throw new IOException("HTTP Error: " + responseCode + " Reason: " + response.getStatusLine().getReasonPhrase()); } return null; } }; futureTask = execService.submit(task); }
From source file:com.btoddb.chronicle.plunkers.FilePlunkerImpl.java
PrintWriter retrievePrintWriter(final String fn) { try {/*from www .j a va 2 s. c o m*/ return printWriterCache.get(fn, new Callable<PrintWriter>() { @Override public PrintWriter call() throws IOException { File f = new File(fn); FileUtils.forceMkdir(f.getParentFile()); return new PrintWriter(new FileWriter(f)); } }); } catch (ExecutionException e) { Utils.logAndThrow(logger, "exception while trying to retrieve PrintWriter from cache", e); return null; } }
From source file:apiserver.services.images.controllers.info.MetadataController.java
/** * get embedded metadata// w w w . j a va 2 s .co m * * @param documentId * @return height, width */ @ApiOperation(value = "Get the embedded metadata", response = Map.class) @RequestMapping(value = "/info/{documentId}/metadata", method = { RequestMethod.GET }) public WebAsyncTask<Map> imageMetadataByImage( @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId) { final String _documentId = documentId; Callable<Map> callable = new Callable<Map>() { @Override public Map call() throws Exception { FileMetadataJob args = new FileMetadataJob(); args.setDocumentId(_documentId); Future<Map> imageFuture = imageMetadataGateway.getMetadata(args); FileMetadataJob payload = (FileMetadataJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS); return payload.getMetadata(); } }; return new WebAsyncTask<Map>(defaultTimeout, callable); }