List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:com.loopj.android.http.sample.AsyncBackgroundThreadSample.java
@Override public ResponseHandlerInterface getResponseHandler() { FutureTask<ResponseHandlerInterface> future = new FutureTask<>(new Callable<ResponseHandlerInterface>() { @Override/* w w w. ja v a 2 s . c om*/ public ResponseHandlerInterface call() throws Exception { Log.d(LOG_TAG, "Creating AsyncHttpResponseHandler on background thread"); return new AsyncHttpResponseHandler(Looper.getMainLooper()) { @Override public void onStart() { clearOutputs(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { Log.d(LOG_TAG, String.format("onSuccess executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper())); debugHeaders(LOG_TAG, headers); debugStatusCode(LOG_TAG, statusCode); debugResponse(LOG_TAG, new String(response)); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { Log.d(LOG_TAG, String.format("onFailure executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper())); debugHeaders(LOG_TAG, headers); debugStatusCode(LOG_TAG, statusCode); debugThrowable(LOG_TAG, e); if (errorResponse != null) { debugResponse(LOG_TAG, new String(errorResponse)); } } @Override public void onRetry(int retryNo) { Toast.makeText(AsyncBackgroundThreadSample.this, String.format("Request is retried, retry no. %d", retryNo), Toast.LENGTH_SHORT) .show(); } }; } }); executor.execute(future); ResponseHandlerInterface responseHandler = null; try { responseHandler = future.get(); Log.d(LOG_TAG, "Background thread for AsyncHttpResponseHandler has finished"); } catch (Exception e) { e.printStackTrace(); } return responseHandler; }
From source file:com.skymobi.monitor.service.TaskService.java
public FutureTask<CommandResult> runScript(final String script, final Project project) { FutureTask<CommandResult> _fuFutureTask = new FutureTask(new Callable() { @Override/*from w w w .j a v a 2 s.c om*/ public CommandResult call() throws Exception { logger.debug("run mongo script = {}", script); CommandResult result = project.fetchMongoTemplate().getDb().doEval(script, new BasicDBObject().append("nolock", true)); logger.debug("mongo task response {}", result); return result; } }); executor.submit(_fuFutureTask); return _fuFutureTask; }
From source file:com.enterra.batch.admin.sample.BootstrapTests.java
@Test public void testServletConfiguration() throws Exception { ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext( "classpath:/org/springframework/batch/admin/web/resources/webapp-config.xml"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml" }, parent);//from w w w . j a v a2 s . com assertTrue(context.containsBean("jobRepository")); String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), JobController.class); assertEquals(1, beanNames.length); Job job = context.getBean(JobRegistry.class).getJob("job1"); final JobExecution jobExecution = parent.getBean(JobLauncher.class).run(job, new JobParametersBuilder().addString("fail", "false").toJobParameters()); new DirectPoller<BatchStatus>(100).poll(new Callable<BatchStatus>() { public BatchStatus call() throws Exception { BatchStatus status = jobExecution.getStatus(); if (status.isLessThan(BatchStatus.STOPPED) && status != BatchStatus.COMPLETED) { return null; } return status; } }).get(2000, TimeUnit.MILLISECONDS); context.close(); parent.close(); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); }
From source file:com.blacklocus.qs.QueueReader.java
@Override public void go() throws Exception { for (Collection<Q> queueItems : queueItemProvider) { try {/*from ww w .j a v a 2 s . c o m*/ if (queueItems.size() > 0) { for (final Q queueItem : queueItems) { handler.withFuture(queueItem, executor.submit(new Callable<Pair<Q, R>>() { public Pair<Q, R> call() throws Exception { T converted = null; R result = null; try { converted = handler.convert(queueItem); result = handler.process(converted); handler.onSuccess(queueItem, converted, result); return Pair.of(queueItem, result); } catch (Throwable t) { LOG.error("An error occurred while processing item {}", queueItem, t); handler.onError(queueItem, converted, t); throw new RuntimeException(t); } finally { handler.onComplete(queueItem, converted, result); } } })); } } else { LOG.debug("No items available... sleeping for {} ms", sleepMs); Thread.sleep(sleepMs); } } catch (InterruptedException e) { LOG.error("Reader thread interrupted", e); Thread.currentThread().interrupt(); } catch (Throwable t) { LOG.error("Runtime error in reader thread", t); } } }
From source file:org.apache.hadoop.gateway.shell.AbstractRequest.java
public Future<T> later(final Closure<Void> closure) { return hadoop().executeLater(new Callable<T>() { @Override//from w w w .j a v a2s .c o m public T call() throws Exception { T result = callable().call(); closure.call(result); return result; } }); }
From source file:com.linuxbox.enkive.message.search.AbstractMessageSearchService.java
@Override @Async/*from w w w. java 2 s . c o m*/ public Future<SearchResult> searchAsync(final Map<String, String> fields) throws MessageSearchException { FutureTask<SearchResult> searchFuture = new FutureTask<SearchResult>(new Callable<SearchResult>() { public SearchResult call() { SearchResult result = null; try { result = search(fields); } catch (MessageSearchException e) { if (LOGGER.isWarnEnabled()) LOGGER.warn("Error Searching for message", e); } return result; } }); searchFuture.run(); return searchFuture; }
From source file:com.googlecode.starflow.engine.handle.BaseHandlerAdapter.java
/** * /*from ww w . j a va 2 s .c o m*/ * * suspend * ? * join???? * suspend?? * * @param event * @param actEl * @param activityXml * @param action * @param activityInst */ public void action(final ActivityStartEvent event, final ActivityInst activityInst, ActivityElement activityXml, final IAction action) { String invokePattern = activityXml.getInvokePattern(); final String transactionType = activityXml.getTransactionType(); ExecutorService executor = event.getProcessEngine().getExecutorService(); if (Constants.ACT_AUTO_CALL_SYN.equalsIgnoreCase(invokePattern)) { Object result = null; //???????? try { result = executor.execute(new Callable<Object>() { @Override public Object call() throws Exception { if (Constants.ACT_TRANSACTION_JOIN.equalsIgnoreCase(transactionType)) { return action.execute(event, activityInst); } else { return executeLogicInNewTransaction(event, activityInst, action); } } }, invokePattern); } catch (Exception e) { handleException(e, event, activityXml); } //? saveResultRelaData(event, result, activityXml); } else { //suspend try { executor.execute(new Callable<Object>() { public Object call() throws Exception { return executeLogicInNewTransaction(event, activityInst, action); } }, invokePattern); } catch (Exception e) { logger.error("Action", e); } } }
From source file:com.microsoft.azure.management.compute.VirtualMachineSizeOperationsImpl.java
/** * Lists virtual-machine-sizes available in a location for a subscription. * * @param location Required. The location upon which virtual-machine-sizes * is queried./*from w w w . j a va 2 s . c o m*/ * @return The List Virtual Machine operation response. */ @Override public Future<VirtualMachineSizeListResponse> listAsync(final String location) { return this.getClient().getExecutorService().submit(new Callable<VirtualMachineSizeListResponse>() { @Override public VirtualMachineSizeListResponse call() throws Exception { return list(location); } }); }
From source file:com.microsoft.windowsazure.management.mediaservices.MediaServiceManagementIntegrationTestBase.java
protected static void createStorageManagementClient() throws Exception { Configuration config = createConfiguration(); config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); storageManagementClient = StorageManagementService.create(config); addClient((ServiceClient<?>) storageManagementClient, new Callable<Void>() { @Override//from w w w. j av a 2 s .co m public Void call() throws Exception { createStorageManagementClient(); return null; } }); }
From source file:net.arp7.HdfsPerfTest.WriteFile.java
private static void writeFiles(final Configuration conf, final FileIoStats stats) throws InterruptedException, IOException { final FileSystem fs = FileSystem.get(conf); final AtomicLong filesLeft = new AtomicLong(params.getNumFiles()); final long runId = abs(rand.nextLong()); final byte[] data = new byte[params.getIoSize()]; Arrays.fill(data, (byte) 65); // Start the writers. final ExecutorService executor = Executors.newFixedThreadPool((int) params.getNumThreads()); final CompletionService<Object> ecs = new ExecutorCompletionService<>(executor); LOG.info("NumFiles=" + params.getNumFiles() + ", FileSize=" + FileUtils.byteCountToDisplaySize(params.getFileSize()) + ", IoSize=" + FileUtils.byteCountToDisplaySize(params.getIoSize()) + ", BlockSize=" + FileUtils.byteCountToDisplaySize(params.getBlockSize()) + ", ReplicationFactor=" + params.getReplication() + ", isThrottled=" + (params.maxWriteBps() > 0)); LOG.info("Starting " + params.getNumThreads() + " writer thread" + (params.getNumThreads() > 1 ? "s" : "") + "."); final long startTime = System.nanoTime(); for (long t = 0; t < params.getNumThreads(); ++t) { final long threadIndex = t; Callable<Object> c = new Callable<Object>() { @Override//ww w .j a v a 2 s. com public Object call() throws Exception { long fileIndex = 0; while (filesLeft.addAndGet(-1) >= 0) { final String fileName = "WriteFile-" + runId + "-" + (threadIndex + 1) + "-" + (++fileIndex); writeOneFile(new Path(params.getOutputDir(), fileName), fs, data, stats); } return null; } }; ecs.submit(c); } // And wait for all writers to complete. for (long t = 0; t < params.getNumThreads(); ++t) { ecs.take(); } final long endTime = System.nanoTime(); stats.setElapsedTime(endTime - startTime); executor.shutdown(); }