List of usage examples for com.google.common.util.concurrent ListenableFuture get
V get() throws InterruptedException, ExecutionException;
From source file:com.continuuity.weave.internal.ZKServiceDecorator.java
@Override protected void doStart() { callbackExecutor = Executors.newSingleThreadExecutor(Threads.createDaemonThreadFactory("message-callback")); Futures.addCallback(createLiveNode(), new FutureCallback<String>() { @Override/*www . j av a 2 s .c om*/ public void onSuccess(String result) { // Create nodes for states and messaging StateNode stateNode = new StateNode(ServiceController.State.STARTING); final ListenableFuture<List<String>> createFuture = Futures.allAsList( deleteAndCreate(getZKPath("messages"), null, CreateMode.PERSISTENT), deleteAndCreate(getZKPath("state"), encodeStateNode(stateNode), CreateMode.PERSISTENT)); createFuture.addListener(new Runnable() { @Override public void run() { try { createFuture.get(); // Starts the decorated service decoratedService.addListener(createListener(), Threads.SAME_THREAD_EXECUTOR); decoratedService.start(); } catch (Exception e) { notifyFailed(e); } } }, Threads.SAME_THREAD_EXECUTOR); } @Override public void onFailure(Throwable t) { notifyFailed(t); } }); }
From source file:org.guldenj.tools.WalletTool.java
private static void sendPaymentRequest(String location, boolean verifyPki) { if (location.startsWith("http") || location.startsWith("bitcoin")) { try {//from w w w .ja v a 2 s . c om ListenableFuture<PaymentSession> future; if (location.startsWith("http")) { future = PaymentSession.createFromUrl(location, verifyPki); } else { GuldenURI paymentRequestURI = new GuldenURI(location); future = PaymentSession.createFromBitcoinUri(paymentRequestURI, verifyPki); } PaymentSession session = future.get(); if (session != null) { send(session); } else { System.err.println("Server returned null session"); System.exit(1); } } catch (PaymentProtocolException e) { System.err.println("Error creating payment session " + e.getMessage()); System.exit(1); } catch (GuldenURIParseException e) { System.err.println("Invalid bitcoin uri: " + e.getMessage()); System.exit(1); } catch (InterruptedException e) { // Ignore. } catch (ExecutionException e) { throw new RuntimeException(e); } } else { // Try to open the payment request as a file. FileInputStream stream = null; try { File paymentRequestFile = new File(location); stream = new FileInputStream(paymentRequestFile); } catch (Exception e) { System.err.println("Failed to open file: " + e.getMessage()); System.exit(1); } try { paymentRequest = org.bitcoin.protocols.payments.Protos.PaymentRequest.newBuilder().mergeFrom(stream) .build(); } catch (IOException e) { System.err.println("Failed to parse payment request from file " + e.getMessage()); System.exit(1); } PaymentSession session = null; try { session = new PaymentSession(paymentRequest, verifyPki); } catch (PaymentProtocolException e) { System.err.println("Error creating payment session " + e.getMessage()); System.exit(1); } send(session); } }
From source file:org.bitcoinj.tools.WalletTool.java
private static void send(PaymentSession session) { try {//from w w w .j ava2 s. co m System.out.println("Payment Request"); System.out.println("Coin: " + session.getValue().toFriendlyString()); System.out.println("Date: " + session.getDate()); System.out.println("Memo: " + session.getMemo()); if (session.pkiVerificationData != null) { System.out.println("Pki-Verified Name: " + session.pkiVerificationData.displayName); System.out.println("PKI data verified by: " + session.pkiVerificationData.rootAuthorityName); } final SendRequest req = session.getSendRequest(); if (password != null) { req.aesKey = passwordToKey(true); if (req.aesKey == null) return; // Error message already printed. } wallet.completeTx(req); // may throw InsufficientMoneyException. if (options.has("offline")) { wallet.commitTx(req.tx); return; } setup(); // No refund address specified, no user-specified memo field. ListenableFuture<PaymentProtocol.Ack> future = session.sendPayment(ImmutableList.of(req.tx), null, null); if (future == null) { // No payment_url for submission so, broadcast and wait. peerGroup.start(); peerGroup.broadcastTransaction(req.tx).future().get(); } else { PaymentProtocol.Ack ack = future.get(); wallet.commitTx(req.tx); System.out.println("Memo from server: " + ack.getMemo()); } } catch (PaymentProtocolException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (VerificationException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (ExecutionException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("Invalid payment " + e.getMessage()); System.exit(1); } catch (InterruptedException e1) { // Ignore. } catch (InsufficientMoneyException e) { System.err.println("Insufficient funds: have " + wallet.getBalance().toFriendlyString()); } catch (BlockStoreException e) { throw new RuntimeException(e); } }
From source file:org.voltdb.export.processors.GuestProcessor.java
private void constructListener(final ExportDataSource source, final ListenableFuture<BBContainer> fut, final ExportDecoderBase edb, final AdvertisedDataSource ads) { /*//from w w w. j a v a 2 s . c om * The listener runs in the thread specified by the EDB. * It can be same thread executor for things like export to file where the destination * is always available and there is no reason to do additional buffering. * * For JDBC we want a dedicated thread to block on calls to the remote database * so the data source thread can overflow data to disk. */ fut.addListener(new Runnable() { @Override public void run() { try { BBContainer cont = fut.get(); if (cont == null) { synchronized (ads) { edb.sourceNoLongerAdvertised(ads); } return; } try { //Position to restart at on error final int startPosition = cont.b.position(); //Track the amount of backoff to use next time, will be updated on repeated failure int backoffQuantity = 10 + (int) (10 * ThreadLocalRandom.current().nextDouble()); /* * If there is an error processing the block the decoder thinks is recoverable * start the block from the beginning and repeat until it is processed. * Also allow the decoder to request exponential backoff */ while (true) { cont.b.position(startPosition); try { edb.onBlockStart(); cont.b.order(ByteOrder.LITTLE_ENDIAN); while (cont.b.hasRemaining()) { int length = cont.b.getInt(); byte[] rowdata = new byte[length]; cont.b.get(rowdata, 0, length); edb.processRow(length, rowdata); } edb.onBlockCompletion(); break; } catch (RestartBlockException e) { if (e.requestBackoff) { Thread.sleep(backoffQuantity); //Cap backoff to 8 seconds, then double modulo some randomness if (backoffQuantity < 8000) { backoffQuantity += (backoffQuantity * .5); backoffQuantity += (backoffQuantity * .5 * ThreadLocalRandom.current().nextDouble()); } } } } } finally { cont.discard(); } } catch (Exception e) { m_logger.error("Error processing export block", e); } constructListener(source, source.poll(), edb, ads); } }, edb.getExecutor()); }
From source file:com.liaison.shachi.test.e2e.test.End2EndSuite1Test3.java
@Override public void runTest(final Verify verifier, final HBaseControl ctrl) throws InterruptedException, ExecutionException, HBaseException { final String testPrefix; ListenableFuture<OpResultSet> opResSetFuture; OpResultSet opResSet;/*from ww w . j a v a 2s .c om*/ String rowKeyStr; String randomData; testPrefix = "test3"; LOG.info(testPrefix, "starting..."); rowKeyStr = Long.toString(System.currentTimeMillis()); randomData = UUID.randomUUID().toString(); LOG.info(testPrefix, "starting write..."); opResSetFuture = ctrl.begin().write(HANDLE_TESTWRITE_3).on().tbl(TEST_MODEL_C).row(RowKey.of(rowKeyStr)) .and().withAllOf(COLUMNQUALS_ABC, (element, spec) -> { spec.fam(FAM_MODEL_a); spec.qual(QualModel.of(Name.of(element))); spec.ts(TS_SAMPLE_1); spec.value(Value.of(element + randomData)); }).then().async().exec(); LOG.info(testPrefix, "write started (async)!"); opResSet = opResSetFuture.get(); LOG.info(testPrefix, "write results: " + opResSet.getResultsByHandle()); LOG.info(testPrefix, "starting read..."); opResSet = ctrl.begin().read(HANDLE_TESTREAD_3).from().tbl(TEST_MODEL_C).row(RowKey.of(rowKeyStr)).and() .with().fam(FAM_MODEL_a).and().atTime().gt(TS_SAMPLE_1 - 10).lt(TS_SAMPLE_1 + 10).and().then() .exec(); LOG.info(testPrefix, "read complete!"); LOG.info(testPrefix, "read results: " + opResSet.getResultsByHandle()); }
From source file:org.apache.twill.internal.ServiceMain.java
protected final void doMain(final Service mainService, Service... prerequisites) throws ExecutionException, InterruptedException { if (Boolean.parseBoolean(System.getProperty("twill.disable.kafka"))) { LOG.info("Log collection through kafka disabled"); } else {/*from w ww .ja v a 2 s . c o m*/ configureLogger(); } Service requiredServices = new CompositeService(prerequisites); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mainService.stopAndWait(); } }); // Listener for state changes of the service ListenableFuture<Service.State> completion = Services.getCompletionFuture(mainService); Throwable initFailure = null; try { try { // Starts the service LOG.info("Starting service {}.", mainService); Futures.allAsList(Services.chainStart(requiredServices, mainService).get()).get(); LOG.info("Service {} started.", mainService); } catch (Throwable t) { LOG.error("Exception when starting service {}.", mainService, t); initFailure = t; } try { if (initFailure == null) { completion.get(); LOG.info("Service {} completed.", mainService); } } catch (Throwable t) { LOG.error("Exception thrown from service {}.", mainService, t); throw Throwables.propagate(t); } } finally { requiredServices.stopAndWait(); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { ((LoggerContext) loggerFactory).stop(); } if (initFailure != null) { // Exit with the init fail exit code. System.exit(ContainerExitCodes.INIT_FAILED); } } }
From source file:com.afewmoreamps.JitCaskImpl.java
@Override public ListenableFuture<RemoveResult> remove(final byte[] key, final boolean waitForSync) { if (key == null) { throw new IllegalArgumentException(); }/* www . ja va 2 s . co m*/ final long start = System.currentTimeMillis(); try { m_maxOutstandingWrites.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } final SettableFuture<RemoveResult> retval = SettableFuture.create(); retval.addListener(new Runnable() { @Override public void run() { m_maxOutstandingWrites.release(); } }, MoreExecutors.sameThreadExecutor()); MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { retval.setException(e); return retval; } final byte keyHash[] = md.digest(key); m_writeThread.execute(new Runnable() { @Override public void run() { KDEntry entry = m_keyDir.get(KeyDir.decorateKeyHash(keyHash)); if (entry == null) { retval.set(new RemoveResult((int) (System.currentTimeMillis() - start))); return; } final MiniCask mc = m_miniCasks.get(entry.fileId); try { putImpl(MiniCask.constructTombstoneEntry(keyHash, entry.fileId, mc.m_timestamp), keyHash, true); } catch (Throwable t) { retval.setException(t); return; } if (waitForSync) { final ListenableFuture<Long> syncTask = m_nextSyncTask; syncTask.addListener(new Runnable() { @Override public void run() { try { retval.set(new RemoveResult((int) (syncTask.get() - start))); } catch (Throwable t) { retval.setException(t); return; } } }, MoreExecutors.sameThreadExecutor()); } else { retval.set(new RemoveResult((int) (System.currentTimeMillis() - start))); } } }); return retval; }
From source file:io.druid.query.AsyncQueryRunner.java
@Override public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final int priority = query.getContextPriority(0); final ListenableFuture<Sequence<T>> future = executor .submit(new AbstractPrioritizedCallable<Sequence<T>>(priority) { @Override//from ww w .j av a2s. co m public Sequence<T> call() throws Exception { //Note: this is assumed that baseRunner does most of the work eagerly on call to the //run() method and resulting sequence accumulate/yield is fast. return baseRunner.run(query, responseContext); } }); queryWatcher.registerQuery(query, future); return new LazySequence<>(new Supplier<Sequence<T>>() { @Override public Sequence<T> get() { try { Number timeout = query.getContextValue(QueryContextKeys.TIMEOUT); if (timeout == null) { return future.get(); } else { return future.get(timeout.longValue(), TimeUnit.MILLISECONDS); } } catch (ExecutionException | InterruptedException | TimeoutException ex) { throw Throwables.propagate(ex); } } }); }
From source file:com.facebook.buck.cli.DistBuildCommandDelegate.java
private ExitCode executeDistBuild(CommandRunnerParams params, BuildCommand buildCommand, DistBuildConfig distBuildConfig, GraphsAndBuildTargets graphsAndBuildTargets, WeightedListeningExecutorService executorService, ProjectFilesystem filesystem, FileHashCache fileHashCache, ClientStatsTracker distBuildClientStats, RuleKeyCacheScope<RuleKey> ruleKeyCacheScope) throws IOException, InterruptedException { Objects.requireNonNull(distBuildClientEventListener); Preconditions.checkArgument(/*from w w w .j a v a 2 s . c om*/ !distBuildConfig.getPerformRuleKeyConsistencyCheck() || distBuildConfig.getLogMaterializationEnabled(), "Log materialization must be enabled to perform rule key consistency check."); if (distributedBuildStateFile == null && distBuildConfig.getBuildMode().equals(BuildMode.DISTRIBUTED_BUILD_WITH_LOCAL_COORDINATOR) && !distBuildConfig.getMinionQueue().isPresent()) { throw new HumanReadableException( "Stampede Minion Queue name must be specified to use Local Coordinator Mode."); } BuildEvent.DistBuildStarted started = BuildEvent.distBuildStarted(); params.getBuckEventBus().post(started); if (!autoDistBuild) { // Enable Stampede console now, but only if it's an explicit stampede build. params.getBuckEventBus().post(new DistBuildSuperConsoleEvent()); } LOG.info("Starting async file hash computation and job state serialization."); RemoteCommand remoteCommand = distBuildConfig .getLocalBuildMode() == DistLocalBuildMode.RULE_KEY_DIVERGENCE_CHECK ? RemoteCommand.RULE_KEY_DIVERGENCE_CHECK : RemoteCommand.BUILD; AsyncJobStateAndCells stateAndCells = AsyncJobStateFactory.computeDistBuildState(params, graphsAndBuildTargets, executorService, Optional.of(distBuildClientStats), remoteCommand); ListenableFuture<BuildJobState> asyncJobState = stateAndCells.getAsyncJobState(); DistBuildCellIndexer distBuildCellIndexer = stateAndCells.getDistBuildCellIndexer(); if (distributedBuildStateFile != null) { BuildJobState jobState; try { jobState = asyncJobState.get(); } catch (ExecutionException e) { throw new RuntimeException("Failed to compute DistBuildState.", e); } // Read all files inline if we're dumping state to a file. for (BuildJobStateFileHashes cell : jobState.getFileHashes()) { ProjectFilesystem cellFilesystem = Objects.requireNonNull( distBuildCellIndexer.getLocalFilesystemsByCellIndex().get(cell.getCellIndex())); for (BuildJobStateFileHashEntry entry : cell.getEntries()) { cellFilesystem.readFileIfItExists(cellFilesystem.resolve(entry.getPath().getPath())) .ifPresent(contents -> entry.setContents(contents.getBytes())); } } Path stateDumpPath = Paths.get(distributedBuildStateFile); BuildJobStateSerializer.serialize(jobState, filesystem.newFileOutputStream(stateDumpPath)); return ExitCode.SUCCESS; } BuckVersion buckVersion = getBuckVersion(); Preconditions.checkArgument(params.getInvocationInfo().isPresent()); distBuildClientStats.setIsLocalFallbackBuildEnabled(distBuildConfig.isSlowLocalBuildFallbackModeEnabled()); try (DistBuildService distBuildService = DistBuildFactory.newDistBuildService(params); RemoteBuildRuleSynchronizer remoteBuildRuleSynchronizer = new RemoteBuildRuleSynchronizer( params.getClock(), params.getScheduledExecutor(), distBuildConfig.getCacheSynchronizationFirstBackoffMillis(), distBuildConfig.getCacheSynchronizationMaxTotalBackoffMillis())) { ListeningExecutorService stampedeControllerExecutor = createStampedeControllerExecutorService( distBuildConfig.getControllerMaxThreadCount()); ListeningExecutorService stampedeLocalBuildExecutor = createStampedeLocalBuildExecutorService(); LogStateTracker distBuildLogStateTracker = DistBuildFactory.newDistBuildLogStateTracker( params.getInvocationInfo().get().getLogDirectoryPath(), filesystem, distBuildService); DistBuildControllerArgs.Builder distBuildControllerArgsBuilder = DistBuildControllerArgs.builder() .setBuilderExecutorArgs(params.createBuilderArgs()).setBuckEventBus(params.getBuckEventBus()) .setDistBuildStartedEvent(started).setTopLevelTargets(graphsAndBuildTargets.getBuildTargets()) .setBuildGraphs(graphsAndBuildTargets.getGraphs()) .setCachingBuildEngineDelegate( Optional.of(new LocalCachingBuildEngineDelegate(params.getFileHashCache()))) .setAsyncJobState(asyncJobState).setDistBuildCellIndexer(distBuildCellIndexer) .setDistBuildService(distBuildService).setDistBuildLogStateTracker(distBuildLogStateTracker) .setBuckVersion(buckVersion).setDistBuildClientStats(distBuildClientStats) .setScheduler(params.getScheduledExecutor()) .setMaxTimeoutWaitingForLogsMillis(distBuildConfig.getMaxWaitForRemoteLogsToBeAvailableMillis()) .setLogMaterializationEnabled(distBuildConfig.getLogMaterializationEnabled()) .setBuildLabel(distBuildConfig.getBuildLabel()); LocalBuildExecutorInvoker localBuildExecutorInvoker = new LocalBuildExecutorInvoker() { @Override public void initLocalBuild(boolean isDownloadHeavyBuild, RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter) { DistBuildCommandDelegate.this.initLocalBuild(params, buildCommand, graphsAndBuildTargets, executorService, Optional.empty(), remoteBuildRuleCompletionWaiter, isDownloadHeavyBuild, ruleKeyCacheScope); } @Override public ExitCode executeLocalBuild(boolean isDownloadHeavyBuild, RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter, CountDownLatch initializeBuildLatch, AtomicReference<Build> buildReference) throws Exception { return buildCommand.executeLocalBuild(params, graphsAndBuildTargets, executorService, Optional.empty(), remoteBuildRuleCompletionWaiter, isDownloadHeavyBuild, Optional.of(initializeBuildLatch), ruleKeyCacheScope, buildReference); } }; DistBuildControllerInvocationArgs distBuildControllerInvocationArgs = DistBuildControllerInvocationArgs .builder().setExecutorService(stampedeControllerExecutor).setProjectFilesystem(filesystem) .setFileHashCache(fileHashCache).setInvocationInfo(params.getInvocationInfo().get()) .setBuildMode(distBuildConfig.getBuildMode()) .setDistLocalBuildMode(distBuildConfig.getLocalBuildMode()) .setMinionRequirements(distBuildConfig.getMinionRequirements()) .setRepository(distBuildConfig.getRepository()).setTenantId(distBuildConfig.getTenantId()) .setRuleKeyCalculatorFuture(localRuleKeyCalculator).build(); // TODO(alisdair): ensure minion build status recorded even if local build finishes first. boolean waitForDistBuildThreadToFinishGracefully = distBuildConfig.getLogMaterializationEnabled(); long distributedBuildThreadKillTimeoutSeconds = distBuildConfig .getDistributedBuildThreadKillTimeoutSeconds(); StampedeBuildClient stampedeBuildClient = new StampedeBuildClient(params.getBuckEventBus(), stampedeLocalBuildExecutor, stampedeControllerExecutor, distBuildService, started, localBuildExecutorInvoker, distBuildControllerArgsBuilder, distBuildControllerInvocationArgs, distBuildClientStats, waitForDistBuildThreadToFinishGracefully, distributedBuildThreadKillTimeoutSeconds, autoDistBuildMessage, remoteBuildRuleSynchronizer); distBuildClientStats.startTimer(PERFORM_LOCAL_BUILD); // Perform either a single phase build that waits for all remote artifacts before proceeding, // or a two stage build where local build first races against remote, and depending on // progress either completes first or falls back to build that waits for remote artifacts. Optional<ExitCode> localExitCodeOption = stampedeBuildClient.build(distBuildConfig.getLocalBuildMode(), distBuildConfig.isSlowLocalBuildFallbackModeEnabled()); ExitCode localExitCode = localExitCodeOption.orElse(ExitCode.FATAL_GENERIC); // All local/distributed build steps are now finished. StampedeId stampedeId = stampedeBuildClient.getStampedeId(); DistributedExitCode distributedBuildExitCode = stampedeBuildClient.getDistBuildExitCode(); distBuildClientStats.setStampedeId(stampedeId.getId()); distBuildClientStats.setDistributedBuildExitCode(distributedBuildExitCode.getCode()); // Set local build stats distBuildClientStats.setPerformedLocalBuild(true); distBuildClientStats.stopTimer(PERFORM_LOCAL_BUILD); distBuildClientStats.setLocalBuildExitCode(localExitCode.getCode()); // If local build finished before hashing was complete, it's important to cancel // related Futures to avoid this operation blocking forever. asyncJobState.cancel(true); // stampedeControllerExecutor is now redundant. Kill it as soon as possible. killExecutor(stampedeControllerExecutor, ("Stampede controller executor service still running after build finished" + " and timeout elapsed. Terminating..")); killExecutor(stampedeLocalBuildExecutor, ("Stampede local build executor service still running after build finished" + " and timeout elapsed. Terminating..")); ExitCode finalExitCode; DistLocalBuildMode distLocalBuildMode = distBuildControllerInvocationArgs.getDistLocalBuildMode(); if (distLocalBuildMode.equals(DistLocalBuildMode.FIRE_AND_FORGET) || distLocalBuildMode.equals(DistLocalBuildMode.RULE_KEY_DIVERGENCE_CHECK)) { finalExitCode = localExitCode; } else { finalExitCode = performPostBuild(params, distBuildConfig, filesystem, distBuildClientStats, stampedeId, distributedBuildExitCode, localExitCode, distBuildService, distBuildLogStateTracker); } // If no local fallback, and there was a stampede infrastructure failure, // then return corresponding exit code if (finalExitCode != ExitCode.SUCCESS && !distBuildConfig.isSlowLocalBuildFallbackModeEnabled() && DistributedExitCode.wasStampedeInfraFailure(distributedBuildExitCode)) { finalExitCode = ExitCode.STAMPEDE_INFRA_ERROR; } return finalExitCode; } }
From source file:com.restfb.DefaultFacebookClient.java
/** * Gets value from from given listenable future asserting that exceptions thrown by * future are limited to FacebookException class. *//* w w w .j a v a 2 s . c o m*/ private <T> T facebookFutureGet(ListenableFuture<T> future) throws FacebookException { try { return future.get(); } catch (InterruptedException e) { throw new FacebookNetworkException("interrupted", e); } catch (ExecutionException e) { assert e.getCause() instanceof FacebookException; throw (FacebookException) e.getCause(); } }