Example usage for com.google.common.util.concurrent Futures getUnchecked

List of usage examples for com.google.common.util.concurrent Futures getUnchecked

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures getUnchecked.

Prototype

@GwtIncompatible("TODO")
public static <V> V getUnchecked(Future<V> future) 

Source Link

Document

Returns the result of calling Future#get() uninterruptibly on a task known not to throw a checked exception.

Usage

From source file:org.onosproject.store.device.impl.ECDeviceStore.java

@Override
public DeviceEvent createOrUpdateDevice(ProviderId providerId, DeviceId deviceId,
        DeviceDescription deviceDescription) {
    NodeId master = mastershipService.getMasterFor(deviceId);
    if (localNodeId.equals(master)) {
        deviceDescriptions.put(new DeviceKey(providerId, deviceId), deviceDescription);
        return refreshDeviceCache(providerId, deviceId);
    } else {//from w  ww .j  a  v  a2 s  . c o m
        DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(providerId, deviceId,
                deviceDescription);
        return Futures.getUnchecked(clusterCommunicator.sendAndReceive(deviceInjectedEvent, DEVICE_INJECTED,
                SERIALIZER::encode, SERIALIZER::decode, master));
    }
}

From source file:zipkin.storage.cassandra.CassandraStorage.java

/** Truncates all the column families, or throws on any failure. */
@VisibleForTesting// ww w  .ja  v a 2 s  . c o  m
void clear() {
    guavaSpanConsumer().clear();
    List<ListenableFuture<?>> futures = new LinkedList<>();
    for (String cf : ImmutableList.of("traces", "dependencies", Tables.SERVICE_NAMES, Tables.SPAN_NAMES,
            Tables.SERVICE_NAME_INDEX, Tables.SERVICE_SPAN_NAME_INDEX, Tables.ANNOTATIONS_INDEX)) {
        futures.add(session.get().executeAsync(format("TRUNCATE %s", cf)));
    }
    Futures.getUnchecked(Futures.allAsList(futures));
}

From source file:com.spotify.helios.testing.TemporaryJob.java

void verifyHealthy() throws AssertionError {
    log.debug("Checking health of {}", job.getImage());
    final JobStatus status = Futures.getUnchecked(client.jobStatus(job.getId()));
    if (status == null) {
        return;/* w w  w  .  j  a v  a2 s. co m*/
    }
    for (final Map.Entry<String, TaskStatus> entry : status.getTaskStatuses().entrySet()) {
        verifyHealthy(entry.getKey(), entry.getValue());
    }
}

From source file:org.jclouds.virtualbox.functions.MastersLoadingCache.java

private String getFilePathOrDownload(String httpUrl, String expectedMd5) throws ExecutionException {
    String fileName = httpUrl.substring(httpUrl.lastIndexOf('/') + 1, httpUrl.length());
    URI provider = providerSupplier.get();
    if (!socketTester.apply(HostAndPort.fromParts(provider.getHost(), provider.getPort()))) {
        throw new RuntimeException("could not connect to virtualbox");
    }// ww w  . java 2 s . c  om
    File file = new File(isosDir, fileName);
    List<Statement> statements = new ImmutableList.Builder<Statement>()
            .add(Statements.saveHttpResponseTo(URI.create(httpUrl), isosDir, fileName)).build();
    StatementList statementList = new StatementList(statements);
    NodeMetadata hostNode = checkNotNull(hardcodedHostToHostNodeMetadata.apply(host.get()), "hostNode");
    ListenableFuture<ExecResponse> future = runScriptOnNodeFactory.submit(hostNode, statementList,
            runAsRoot(false));
    Futures.getUnchecked(future);

    if (expectedMd5 != null) {
        String filePath = isosDir + File.separator + fileName;
        ListenableFuture<ExecResponse> md5future = runScriptOnNodeFactory.submit(hostNode, new Md5(filePath),
                runAsRoot(false));

        ExecResponse responseMd5 = Futures.getUnchecked(md5future);
        assert responseMd5.getExitStatus() == 0 : hostNode.getId() + ": " + responseMd5;
        checkNotNull(responseMd5.getOutput(), "iso_md5 missing");
        String actualMd5 = responseMd5.getOutput().trim();
        checkState(actualMd5.equals(expectedMd5), "md5 of %s is %s but expected %s", filePath, actualMd5,
                expectedMd5);
    }
    return file.getAbsolutePath();
}

From source file:co.cask.cdap.internal.app.runtime.distributed.AbstractProgramTwillRunnable.java

@Override
public void destroy() {
    LOG.info("Releasing resources: {}", name);
    if (program != null) {
        Closeables.closeQuietly(program);
    }//  ww  w. j a  v  a2  s  .  co m
    Futures.getUnchecked(Services.chainStop(resourceReporter, streamCoordinatorClient, metricsCollectionService,
            kafkaClientService, zkClientService));
    LOG.info("Runnable stopped: {}", name);
}

From source file:co.cask.cdap.internal.app.runtime.distributed.ServiceTwillRunnable.java

@Override
public void destroy() {
    LOG.info("Releasing resources: {}", name);
    try {//w w w .  j a  v a2  s . com
        delegate.destroy();
    } finally {
        Futures.getUnchecked(Services.chainStop(resourceReporter, metricsCollectionService, kafkaClientService,
                zkClientService));
    }
    LOG.info("Runnable stopped: {}", name);
}

From source file:com.palantir.atlasdb.cleaner.Scrubber.java

private void runBackgroundScrubTask(final TransactionManager txManager) {
    log.info("Starting scrub task");

    // Warning: Let T be the hard delete transaction that triggered a scrub, and let S be its
    // start timestamp.  If the locks for T happen to time out right after T checks that its
    // locks are held but right before T writes its commit timestamp (extremely rare case), AND
    // the unreadable timestamp is greater than S, then the scrub task could actually roll back
    // the hard delete transaction (forcing it to abort or retry).  Note that this doesn't affect
    // correctness, but could be an annoying edge cause that causes hard delete to take longer
    // than it otherwise would have.
    Long immutableTimestamp = immutableTimestampSupplier.get();
    Long unreadableTimestamp = unreadableTimestampSupplier.get();
    final long maxScrubTimestamp = aggressiveScrub ? immutableTimestamp
            : Math.min(unreadableTimestamp, immutableTimestamp);
    if (log.isInfoEnabled()) {
        log.info("Scrub task immutableTimestamp: " + immutableTimestamp + ", unreadableTimestamp: "
                + unreadableTimestamp + ", min: " + maxScrubTimestamp);
    }//  ww  w  .  j  a  v a 2s .c o  m
    final int batchSize = ((int) Math.ceil(batchSizeSupplier.get() * ((double) threadCount / readThreadCount)));

    List<byte[]> rangeBoundaries = Lists.newArrayList();
    rangeBoundaries.add(PtBytes.EMPTY_BYTE_ARRAY);
    if (readThreadCount > 1) {
        // This will actually partition into the closest higher power of 2 number of ranges.
        rangeBoundaries.addAll(Ordering.from(UnsignedBytes.lexicographicalComparator())
                .sortedCopy(new UniformRowNamePartitioner(ValueType.BLOB).getPartitions(readThreadCount - 1)));
    }
    rangeBoundaries.add(PtBytes.EMPTY_BYTE_ARRAY);

    List<Future<Void>> readerFutures = Lists.newArrayList();
    final AtomicInteger totalCellsRead = new AtomicInteger(0);
    for (int i = 0; i < rangeBoundaries.size() - 1; i++) {
        final byte[] startRow = rangeBoundaries.get(i);
        final byte[] endRow = rangeBoundaries.get(i + 1);
        readerFutures.add(readerExec.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                BatchingVisitable<SortedMap<Long, Multimap<String, Cell>>> scrubQueue = scrubberStore
                        .getBatchingVisitableScrubQueue(batchSize, maxScrubTimestamp, startRow, endRow);
                // Take one at a time since we already batched them together in KeyValueServiceScrubberStore.
                BatchingVisitableView.of(scrubQueue).batchAccept(1,
                        new AbortingVisitor<List<SortedMap<Long, Multimap<String, Cell>>>, RuntimeException>() {
                            @Override
                            public boolean visit(List<SortedMap<Long, Multimap<String, Cell>>> batch) {
                                for (SortedMap<Long, Multimap<String, Cell>> cells : batch) {
                                    // We may actually get more cells than the batch size. The batch size is used for pulling off the scrub queue,
                                    // and a single entry in the scrub queue may match multiple tables.
                                    // These will get broken down into smaller batches later on when we actually do deletes.
                                    int numCellsRead = scrubSomeCells(cells, txManager, maxScrubTimestamp);
                                    int totalRead = totalCellsRead.addAndGet(numCellsRead);
                                    if (log.isInfoEnabled()) {
                                        log.info("Scrub task processed " + numCellsRead
                                                + " cells in a batch, total " + totalRead
                                                + " processed so far.");
                                    }
                                    if (!isScrubEnabled.get()) {
                                        log.info("Stopping scrub for banned hours.");
                                        break;
                                    }
                                }
                                return isScrubEnabled.get();
                            }
                        });
                return null;
            }
        }));
    }

    for (Future<Void> readerFuture : readerFutures) {
        Futures.getUnchecked(readerFuture);
    }

    log.info("Scrub background task running at timestamp " + maxScrubTimestamp + " processed a total of "
            + totalCellsRead.get() + " cells");

    log.info("Finished scrub task");
}

From source file:com.android.contacts.activities.AttachPhotoActivity.java

private void selectAccountAndCreateContact() {
    Preconditions.checkNotNull(mAccountsFuture, "Accounts future must be initialized first");
    // If there is no default account or the accounts have changed such that we need to
    // prompt the user again, then launch the account prompt.
    final ContactEditorUtils editorUtils = ContactEditorUtils.create(this);

    // Technically this could block but in reality this method won't be called until the user
    // presses the save button which should allow plenty of time for the accounts to
    // finish loading. Note also that this could be stale if the accounts have changed since
    // we requested them but that's OK since ContactEditorAccountsChangedActivity will reload
    // the accounts
    final List<AccountInfo> accountInfos = Futures.getUnchecked(mAccountsFuture);

    final List<AccountWithDataSet> accounts = AccountInfo.extractAccounts(accountInfos);
    if (editorUtils.shouldShowAccountChangedNotification(accounts)) {
        Intent intent = new Intent(this, ContactEditorAccountsChangedActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, REQUEST_PICK_DEFAULT_ACCOUNT_FOR_NEW_CONTACT);
    } else {/*from w  w w.  j av a  2 s . c  o m*/
        // Otherwise, there should be a default account. Then either create a null contact
        // (if default account is null) or create a contact with the specified account.
        final AccountWithDataSet targetAccount = editorUtils.getOnlyOrDefaultAccount(accounts);
        createNewRawContact(targetAccount);
    }
}

From source file:org.apache.twill.internal.appmaster.RunningContainers.java

/**
 * Stops all running services. Only called when the AppMaster stops.
 *//*ww  w . j a v a  2 s. co m*/
void stopAll() {
    containerLock.lock();
    // Stop the runnables one by one in reverse order of start sequence
    List<String> reverseRunnables = new LinkedList<>();
    try {
        Iterators.addAll(reverseRunnables, startSequence.descendingIterator());
    } finally {
        containerLock.unlock();
    }

    List<ListenableFuture<Service.State>> futures = Lists.newLinkedList();
    for (String runnableName : reverseRunnables) {
        LOG.info("Stopping all instances of " + runnableName);

        futures.clear();
        // Parallel stops all running containers of the current runnable.
        containerLock.lock();
        try {
            for (TwillContainerController controller : containers.row(runnableName).values()) {
                futures.add(controller.stop());
            }
        } finally {
            containerLock.unlock();
        }
        // Wait for containers to stop. Assumes the future returned by Futures.successfulAsList won't throw exception.
        // This will block until handleCompleted() is run for the runnables or a timeout occurs.
        Futures.getUnchecked(Futures.successfulAsList(futures));

        LOG.info("Terminated all instances of " + runnableName);
    }

    // When we acquire this lock, all stopped runnables should have been cleaned up by handleCompleted() method
    containerLock.lock();
    try {
        for (Map.Entry<String, Map<String, TwillContainerController>> entry : containers.rowMap().entrySet()) {
            String runnableName = entry.getKey();
            Collection<ContainerInfo> containerInfos = containerStats.get(runnableName);
            for (Map.Entry<String, TwillContainerController> containerControllerEntry : entry.getValue()
                    .entrySet()) {
                for (ContainerInfo containerInfo : containerInfos) {
                    if (containerInfo.getId().equals(containerControllerEntry.getKey())) {
                        // Only call eventHandler.containerStopped if container is not removed by handleCompleted
                        eventHandler.containerStopped(runnableName,
                                containerControllerEntry.getValue().getInstanceId(),
                                containerControllerEntry.getKey(), ContainerExitCodes.ABORTED);
                        break;
                    }
                }
            }
        }
        containers.clear();
        runnableInstances.clear();
        numRetries.clear();
        containerStats.clear();
    } finally {
        containerLock.unlock();
    }
}

From source file:com.google.sha1coin.tools.WalletTool.java

private static void rotate() throws BlockStoreException {
    setup();//from w  ww.  jav a 2s  .  c  o m
    peers.startAsync();
    peers.awaitRunning();
    // Set a key rotation time and possibly broadcast the resulting maintenance transactions.
    long rotationTimeSecs = Utils.currentTimeSeconds();
    if (options.has(dateFlag)) {
        rotationTimeSecs = options.valueOf(dateFlag).getTime() / 1000;
    }
    log.info("Setting wallet key rotation time to {}", rotationTimeSecs);
    wallet.setKeyRotationEnabled(true);
    wallet.setKeyRotationTime(rotationTimeSecs);
    KeyParameter aesKey = null;
    if (wallet.isEncrypted()) {
        aesKey = passwordToKey(true);
        if (aesKey == null)
            return;
    }
    Futures.getUnchecked(wallet.maybeDoMaintenance(aesKey, true));
}