List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:com.rogiel.httpchannel.http.Request.java
public Future<HttpResponse> requestAsync() throws IOException { return ctx.threadPool.submit(new Callable<HttpResponse>() { @Override/*ww w.j ava 2 s.c o m*/ public HttpResponse call() throws Exception { return request(); } }); }
From source file:com.linkedin.pinot.common.segment.fetcher.HttpSegmentFetcher.java
@Override public void fetchSegmentToLocal(final String uri, final File tempFile) throws Exception { RetryPolicies.exponentialBackoffRetryPolicy(_retryCount, _retryWaitMs, 5).attempt(new Callable<Boolean>() { @Override//ww w . j a v a 2 s . com public Boolean call() throws Exception { try { int statusCode = _httpClient.downloadFile(new URI(uri), tempFile); _logger.info( "Downloaded file from: {} to: {}; Length of downloaded file: {}; Response status code: {}", uri, tempFile, tempFile.length(), statusCode); return true; } catch (HttpErrorStatusException e) { int statusCode = e.getStatusCode(); if (statusCode >= 500) { // Temporary exception _logger.warn("Caught temporary exception while downloading file from: {}, will retry", uri, e); return false; } else { // Permanent exception _logger.error("Caught permanent exception while downloading file from: {}, won't retry", uri, e); throw e; } } catch (Exception e) { _logger.warn("Caught temporary exception while downloading file from: {}, will retry", uri, e); return false; } } }); }
From source file:aos.camel.JavaFutureTest.java
@Test public void testFutureWithDone() 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);/*from 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"); // test when we are done boolean done = false; while (!done) { done = future.isDone(); LOG.info("Is the task done? " + done); if (!done) { Thread.sleep(2000); } } // and get the answer String answer = future.get(); LOG.info("The answer is: " + answer); }
From source file:cherry.foundation.mail.SendMailBatchTest.java
@Test public void testNormal() throws Exception { final File shutdownTrigger = new File("./shutdownTrigger.txt"); shutdownTrigger.deleteOnExit();/*from ww w .j a v a 2 s . c o m*/ 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, false); 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, atLeastOnce()).sendMessage(eq(2L)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L)); }
From source file:no.ntnu.idi.socialhitchhiking.map.RouteProvider.java
/** * Returning a {@link MapRoute}, containing data that is retrieved from Google Maps. * //w w w . ja v a 2 s . c o m * @param fromLat The latitude where the route starts. * @param fromLon The longitude where the route starts. * @param toLat The latitude where the route ends. * @param toLon The latitude where the route ends. * @return Returns a {@link MapRoute} containing all the map data needed for showing a route in a map view. * @throws MalformedURLException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws XmlPullParserException */ public static MapRoute getRoute(double fromLat, double fromLon, double toLat, double toLon, final boolean drawable) throws MalformedURLException, IOException, XmlPullParserException { final String url = RouteProvider.getUrl(fromLat, fromLon, toLat, toLon); ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<MapRoute> callable = new Callable<MapRoute>() { @Override public MapRoute call() throws ClientProtocolException, IOException, XmlPullParserException { InputStream is = RouteProvider.getConnectionInputStream(url); MapRoute temp = new MapRoute(); temp = RouteProvider.getRoute(is, drawable); return temp; } }; Future<MapRoute> future = executor.submit(callable); MapRoute ret; try { ret = future.get(); } catch (InterruptedException e) { ret = null; } catch (ExecutionException e) { // TODO Auto-generated catch block ret = null; } executor.shutdown(); return ret; }
From source file:com.microsoft.windowsazure.management.scheduler.SchedulerIntegrationTestBase.java
protected static void createSchedulerManagementService() throws Exception { Configuration config = createConfiguration(); config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); schedulerManagementClient = SchedulerManagementService.create(config); addClient((ServiceClient<?>) schedulerManagementClient, new Callable<Void>() { @Override/*w ww . j a v a 2 s . c o m*/ public Void call() throws Exception { createSchedulerManagementService(); return null; } }); }
From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedBarrier.java
@Test public void testServerCrash() throws Exception { final int TIMEOUT = 1000; final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) .connectionTimeoutMs(TIMEOUT).retryPolicy(new RetryOneTime(1)).build(); try {/* w w w .j a v a 2 s. c o m*/ client.start(); final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); final ExecutorService service = Executors.newSingleThreadExecutor(); Future<Object> future = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { Thread.sleep(TIMEOUT / 2); server.stop(); return null; } }); barrier.waitOnBarrier(TIMEOUT * 2, TimeUnit.SECONDS); future.get(); Assert.fail(); } catch (KeeperException.ConnectionLossException expected) { // expected } finally { client.close(); } }
From source file:com.github.jknack.handlebars.cache.GuavaTemplateCache.java
@Override public Template get(final TemplateSource source, final Parser parser) throws IOException { notNull(source, "The source is required."); notNull(parser, "The parser is required."); try {/*ww w. j a v a 2 s . co m*/ return cache.get(source, new Callable<Template>() { @Override public Template call() throws IOException { return parser.parse(source); } }); } catch (ExecutionException ex) { throw launderThrowable(source, ex.getCause()); } }
From source file:org.apache.lucene.replicator.http.HttpReplicator.java
@Override public SessionToken checkForUpdate(String currVersion) throws IOException { String[] params = null;//from w w w . j a v a 2s . co m if (currVersion != null) { params = new String[] { ReplicationService.REPLICATE_VERSION_PARAM, currVersion }; } final HttpResponse response = executeGET(ReplicationAction.UPDATE.name(), params); return doAction(response, new Callable<SessionToken>() { @Override public SessionToken call() throws Exception { final DataInputStream dis = new DataInputStream(responseInputStream(response)); try { if (dis.readByte() == 0) { return null; } else { return new SessionToken(dis); } } finally { dis.close(); } } }); }
From source file:org.zenoss.zep.dao.impl.DaoUtilsTest.java
@Test public void testDeadlockRetryNestedException() throws Exception { final AtomicInteger i = new AtomicInteger(); final int returnVal = new Random().nextInt(); int result = DaoUtils.deadlockRetry(new Callable<Integer>() { @Override//from w w w. j a v a2s. co m public Integer call() throws Exception { if (i.incrementAndGet() < 5) { throw new RuntimeException(new DeadlockLoserDataAccessException("My fake exception", null)); } return returnVal; } }); assertEquals(i.get(), 5); assertEquals(result, returnVal); }