List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:com.microsoft.windowsazure.management.compute.ComputeManagementIntegrationTestBase.java
protected static void createStorageManagementClient() throws Exception { Configuration config = createConfiguration(); storageManagementClient = StorageManagementService.create(config); addClient((ServiceClient<?>) storageManagementClient, new Callable<Void>() { @Override/*from ww w .j ava2s. c o m*/ public Void call() throws Exception { createStorageManagementClient(); return null; } }); addRegexRule("storageservices/aztst[a-z]{10}"); }
From source file:es.upv.grycap.coreutils.fiber.test.FetchCancellationTest.java
@Test public void testFetch() throws Exception { // create fetcher final HttpDataFetcher fetcher = new HttpDataFetcher(2); assertThat("Fetcher was created", fetcher, notNullValue()); // create output folder final File outDir = tmpFolder.newFolder(randomAlphanumeric(12)); assertThat("Output dir was created", outDir, notNullValue()); assertThat("Output dir is writable", outDir.canWrite()); // submit request and cancel final ExecutorService executorService = Executors.newFixedThreadPool(2); final Future<Map<String, FetchStatus>> future = executorService .submit(new Callable<Map<String, FetchStatus>>() { @Override/*ww w.ja va 2 s . c o m*/ public Map<String, FetchStatus> call() throws Exception { return AsyncCompletionStage .get(fetcher.fetchToDir(new URL(MOCK_SERVER_BASE_URL + "/fetch/long-waiting"), ImmutableList.of("1"), outDir), 120000l, TimeUnit.SECONDS); } }); assertThat("Request was cancelled", future.cancel(true)); assertThat("File does not exist", not(new File(outDir, "1").exists())); }
From source file:cn.vko.cache.dao.ha.FailoverMonitorJob.java
@Override public void run() { Future<Integer> future = executor.submit(new Callable<Integer>() { @Override/*from w w w . j a va 2 s .c om*/ public Integer call() throws Exception { Integer result = -1; for (int i = 0; i < getRecheckTimes(); i++) { Connection conn = null; try { conn = getCurrentDetectorDataSource().getConnection(); PreparedStatement pstmt = conn.prepareStatement(getDetectingSQL()); pstmt.execute(); pstmt.close(); result = 0; break; } catch (Exception e) { logger.warn("(" + (i + 1) + ") check with failure. sleep (" + getRecheckInterval() + ") for next round check."); try { TimeUnit.MILLISECONDS.sleep(getRecheckInterval()); } catch (InterruptedException e1) { logger.warn("interrupted when waiting for next round rechecking."); } continue; } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { logger.warn("failed to close checking connection:\n", e); } } } } return result; } }); try { Integer result = future.get(getDetectingRequestTimeout(), TimeUnit.MILLISECONDS); if (result == -1) { doSwap(); } } catch (InterruptedException e) { logger.warn("interrupted when getting query result in FailoverMonitorJob."); } catch (ExecutionException e) { logger.warn("exception occured when checking failover status in FailoverMonitorJob"); } catch (TimeoutException e) { logger.warn("exceed DetectingRequestTimeout threshold. Switch to standby data source."); doSwap(); } }
From source file:com.rogiel.httpchannel.http.Request.java
public Future<Page> asPageAsync() throws IOException { return ctx.threadPool.submit(new Callable<Page>() { @Override/*from w ww.j av a 2s . co m*/ public Page call() throws Exception { return asPage(); } }); }
From source file:com.alibaba.cobar.client.datasources.ha.FailoverMonitorJob.java
public void run() { Future<Integer> future = executor.submit(new Callable<Integer>() { public Integer call() throws Exception { Integer result = -1;/*from w w w . j ava 2 s. c o m*/ for (int i = 0; i < getRecheckTimes(); i++) { Connection conn = null; try { conn = getCurrentDetectorDataSource().getConnection(); PreparedStatement pstmt = conn.prepareStatement(getDetectingSQL()); pstmt.execute(); if (pstmt != null) { pstmt.close(); } result = 0; break; } catch (Exception e) { logger.warn("(" + (i + 1) + ") check with failure. sleep (" + getRecheckInterval() + ") for next round check."); try { TimeUnit.MILLISECONDS.sleep(getRecheckInterval()); } catch (InterruptedException e1) { logger.warn("interrupted when waiting for next round rechecking."); } continue; } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { logger.warn("failed to close checking connection:\n", e); } } } } return result; } }); try { Integer result = future.get(getDetectingRequestTimeout(), TimeUnit.MILLISECONDS); if (result == -1) { doSwap(); } } catch (InterruptedException e) { logger.warn("interrupted when getting query result in FailoverMonitorJob."); } catch (ExecutionException e) { logger.warn("exception occured when checking failover status in FailoverMonitorJob"); } catch (TimeoutException e) { logger.warn("exceed DetectingRequestTimeout threshold. Switch to standby data source."); doSwap(); } }
From source file:mx.com.gaby.controller.HomeController.java
@RequestMapping(value = "/views/async", method = RequestMethod.GET) public Callable<String> getViewAsyncWay() { return new Callable<String>() { @Override/*from w w w .j a va2 s . co m*/ public String call() throws Exception { Thread.sleep(5000); return "redir"; } }; }
From source file:biz.c24.io.spring.integration.samples.fpml.PreRenderingFpmlGenerator.java
private List<Generator> preRender() throws Exception { List<Generator> result = new ArrayList<Generator>(THREADS); final TradeConfirmed tradeConfirmed = readTradeConfirmed(); ExecutorCompletionService<Generator> completionService = new ExecutorCompletionService<Generator>( Executors.newFixedThreadPool(THREADS)); for (int i = 0; i < THREADS; i++) { completionService.submit(new Callable<Generator>() { public Generator call() throws Exception { System.out.println("Rendering... "); OutputType ot = OutputType.BYTE_ARRAY; Random rand = new Random(); TradeConfirmed myTradeConfirmed = (TradeConfirmed) tradeConfirmed.cloneDeep(); Generator gen = new Generator(); List<Object> payloads = new ArrayList<Object>(ITERATIONS); for (int j = 0; j < ITERATIONS; j++) { TradeConfirmed fpML = randomizeFpML(myTradeConfirmed); if (rand.nextInt(100) == 0) { breakFpml(fpML); }//from w w w . j av a2 s. c o m Sink sink = ot.getSink(sinkFactory); sink.writeObject(fpML); Object payload = ot.getOutput(sink); payloads.add(payload); } gen.payloads = payloads; return gen; } }); } for (int i = 0; i < THREADS; i++) { Future<Generator> future = completionService.take(); result.add(future.get()); } return result; }
From source file:com.atomicleopard.thundr.ftp.FtpSession.java
public boolean putFile(final String filename, final InputStream is) { return timeLogAndCatch("Put file", new Callable<Boolean>() { @Override//from w w w .j a v a 2 s .co m public Boolean call() throws Exception { return preparedClient.storeFile(filename, is); } }); }
From source file:com.tesobe.obp.transport.spi.ConnectorNov2016Test.java
@Before public void connector() { Transport.Factory factory = Transport.factory(Transport.Version.Nov2016, Transport.Encoding.json) .map(Function.identity()).orElseThrow(IllegalArgumentException::new); Receiver receiver = new ReceiverNov2016(new MockResponder(), factory.codecs()); final BlockingQueue<String> in = new SynchronousQueue<>(); final BlockingQueue<Message> out = new SynchronousQueue<>(); final Sender sender = request -> { out.put(request);/* w w w .ja v a 2s . c o m*/ return in.take(); }; // north: sender connector = factory.connector(sender); // south: receiver in a background thread service.submit(new Callable<Void>() { @Override @SuppressWarnings({ "InfiniteLoopStatement" }) public Void call() throws InterruptedException { for (;;) { in.put(receiver.respond(out.take())); } } }); }
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 . j a va 2 s . c o 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); } }