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.primitives.impl.DefaultDistributedQueue.java

protected void tryPoll() {
    Set<CompletableFuture<E>> completedFutures = Sets.newHashSet();
    for (CompletableFuture<E> future : pendingFutures) {
        E entry = Futures
                .getUnchecked(database.queuePop(name).thenApply(v -> v != null ? serializer.decode(v) : null));
        if (entry != null) {
            future.complete(entry);//w  w  w  .  j a v  a 2s.c om
            completedFutures.add(future);
        } else {
            break;
        }
    }
    pendingFutures.removeAll(completedFutures);
}

From source file:org.jenkinsci.plugins.mesos.MesosCleanupThread.java

@Override
protected void execute(TaskListener listener) {
    final ImmutableList.Builder<ListenableFuture<?>> deletedNodesBuilder = ImmutableList
            .<ListenableFuture<?>>builder();
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Computer.threadPoolForRemoting);
    final ImmutableList.Builder<MesosComputer> computersToDeleteBuilder = ImmutableList
            .<MesosComputer>builder();

    for (final Computer c : Jenkins.getInstance().getComputers()) {
        if (MesosComputer.class.isInstance(c)) {
            MesosSlave mesosSlave = (MesosSlave) c.getNode();

            if (mesosSlave != null && mesosSlave.isPendingDelete()) {
                final MesosComputer comp = (MesosComputer) c;
                computersToDeleteBuilder.add(comp);
                logger.log(Level.INFO, "Marked " + comp.getName() + " for deletion");
                ListenableFuture<?> f = executor.submit(new Runnable() {
                    public void run() {
                        logger.log(Level.INFO, "Deleting pending node " + comp.getName());
                        try {
                            comp.getNode().terminate();
                        } catch (RuntimeException e) {
                            logger.log(Level.WARNING, "Failed to disconnect and delete " + comp.getName() + ": "
                                    + e.getMessage());
                            throw e;
                        }//from  w  ww.jav  a  2 s.c om
                    }
                });
                deletedNodesBuilder.add(f);
            } else {
                logger.log(Level.FINE, c.getName() + " with slave " + mesosSlave
                        + " is not pending deletion or the slave is null");
            }
        } else {
            logger.log(Level.FINER,
                    c.getName() + " is not a mesos computer, it is a " + c.getClass().getName());
        }
    }

    Futures.getUnchecked(Futures.successfulAsList(deletedNodesBuilder.build()));

    for (MesosComputer c : computersToDeleteBuilder.build()) {
        try {
            c.deleteSlave();
        } catch (IOException e) {
            logger.log(Level.WARNING, "Failed to disconnect and delete " + c.getName() + ": " + e.getMessage());
        } catch (InterruptedException e) {
            logger.log(Level.WARNING, "Failed to disconnect and delete " + c.getName() + ": " + e.getMessage());
        }

    }
}

From source file:com.continuuity.loom.common.zookeeper.IdService.java

private void initializeCounter(Type type) {
    Stat stat = Futures.getUnchecked(zkClient.exists(type.path));
    if (stat == null) {
        Futures.getUnchecked(/*from   w w w. j ava2s . co  m*/
                zkClient.create(type.path, Longs.toByteArray(startId), CreateMode.PERSISTENT, true));
    }
}

From source file:com.continuuity.weave.internal.WeaveContainerMain.java

private static Service wrapService(final ZKClientService zkClientService, final Service containerService) {
    return new Service() {

        @Override/*from   w  ww.  j a va 2 s  . co m*/
        public ListenableFuture<State> start() {
            return Futures.transform(Services.chainStart(zkClientService, containerService),
                    new AsyncFunction<List<ListenableFuture<State>>, State>() {
                        @Override
                        public ListenableFuture<State> apply(List<ListenableFuture<State>> input)
                                throws Exception {
                            return input.get(1);
                        }
                    });
        }

        @Override
        public State startAndWait() {
            return Futures.getUnchecked(start());
        }

        @Override
        public boolean isRunning() {
            return containerService.isRunning();
        }

        @Override
        public State state() {
            return containerService.state();
        }

        @Override
        public ListenableFuture<State> stop() {
            return Futures.transform(Services.chainStop(containerService, zkClientService),
                    new AsyncFunction<List<ListenableFuture<State>>, State>() {
                        @Override
                        public ListenableFuture<State> apply(List<ListenableFuture<State>> input)
                                throws Exception {
                            return input.get(0);
                        }
                    });
        }

        @Override
        public State stopAndWait() {
            return Futures.getUnchecked(stop());
        }

        @Override
        public void addListener(Listener listener, Executor executor) {
            containerService.addListener(listener, executor);
        }
    };
}

From source file:google.registry.backup.GcsDiffFileLister.java

List<GcsFileMetadata> listDiffFiles(DateTime fromTime) {
    logger.info("Requested restore from time: " + fromTime);
    // List all of the diff files on GCS and build a map from each file's upper checkpoint time
    // (extracted from the filename) to its asynchronously-loaded metadata, keeping only files with
    // an upper checkpoint time > fromTime.
    Map<DateTime, ListenableFuture<GcsFileMetadata>> upperBoundTimesToMetadata = new HashMap<>();
    Iterator<ListItem> listItems;
    try {//from  w  ww. j  a v  a 2 s  .com
        // TODO(b/23554360): Use a smarter prefixing strategy to speed this up.
        listItems = gcsService.list(gcsBucket, new ListOptions.Builder().setPrefix(DIFF_FILE_PREFIX).build());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    DateTime lastUpperBoundTime = START_OF_TIME;
    while (listItems.hasNext()) {
        final String filename = listItems.next().getName();
        DateTime upperBoundTime = DateTime.parse(filename.substring(DIFF_FILE_PREFIX.length()));
        if (isBeforeOrAt(fromTime, upperBoundTime)) {
            upperBoundTimesToMetadata.put(upperBoundTime, executor.submit(new Callable<GcsFileMetadata>() {
                @Override
                public GcsFileMetadata call() throws Exception {
                    return getMetadata(filename);
                }
            }));
        }
        lastUpperBoundTime = latestOf(upperBoundTime, lastUpperBoundTime);
    }
    if (upperBoundTimesToMetadata.isEmpty()) {
        logger.info("No files found");
        return ImmutableList.of();
    }
    // GCS file listing is eventually consistent, so it's possible that we are missing a file. The
    // metadata of a file is sufficient to identify the preceding file, so if we start from the
    // last file and work backwards we can verify that we have no holes in our chain (although we
    // may be missing files at the end).
    ImmutableList.Builder<GcsFileMetadata> filesBuilder = new ImmutableList.Builder<>();
    logger.info("Restoring until: " + lastUpperBoundTime);
    DateTime checkpointTime = lastUpperBoundTime;
    while (checkpointTime.isAfter(fromTime)) {
        GcsFileMetadata metadata;
        if (upperBoundTimesToMetadata.containsKey(checkpointTime)) {
            metadata = Futures.getUnchecked(upperBoundTimesToMetadata.get(checkpointTime));
        } else {
            String filename = DIFF_FILE_PREFIX + checkpointTime;
            logger.info("Patching GCS list; discovered file " + filename);
            metadata = getMetadata(filename);
            checkState(metadata != null, "Could not read metadata for file %s", filename);
        }
        filesBuilder.add(metadata);
        checkpointTime = getLowerBoundTime(metadata);
    }
    ImmutableList<GcsFileMetadata> files = filesBuilder.build().reverse();
    logger.info("Actual restore from time: " + getLowerBoundTime(files.get(0)));
    logger.infofmt("Found %d files to restore", files.size());
    return files;
}

From source file:com.github.parboiled1.grappa.backport.buffers.CharSequenceInputBuffer.java

@Override
public Position getPosition(final int index) {
    return Futures.getUnchecked(lineCounter).toPosition(index);
}

From source file:com.palantir.atlasdb.schema.KeyValueServiceValidator.java

private void validateTables(Set<TableReference> tables) {
    ExecutorService executor = PTExecutors.newFixedThreadPool(threads);
    List<Future<Void>> futures = Lists.newArrayList();
    for (final TableReference table : tables) {
        Future<Void> future = executor.submit(new Callable<Void>() {
            @Override//w w  w  .ja  v a2  s  .co  m
            public Void call() {
                try {
                    validateTable(table);
                } catch (RuntimeException e) {
                    Throwables.rewrapAndThrowUncheckedException("Exception while validating " + table, e);
                }
                return null;
            }
        });
        futures.add(future);
    }

    futures.forEach(future -> Futures.getUnchecked(future));
}

From source file:com.facebook.buck.core.rules.resolver.impl.MultiThreadedActionGraphBuilder.java

@Override
public Optional<BuildRule> getRuleOptional(BuildTarget buildTarget) {
    Preconditions.checkState(isValid);/*  ww w. j a  va 2 s  . c  o  m*/
    return Optional.ofNullable(buildRuleIndex.get(buildTarget))
            .flatMap(future -> future.isBeingWorkedOnByCurrentThread() ? Optional.empty()
                    : Optional.ofNullable(Futures.getUnchecked(future)));
}

From source file:org.apache.aurora.scheduler.mesos.VersionedSchedulerDriverService.java

@Override
public void acceptOffers(OfferID offerId, Collection<Operation> operations, Filters filter) {
    whenRegistered(() -> {//from w  w  w.  ja  va 2  s.  co  m
        Collection<Operation.Type> opTypes = Collections2.transform(operations, Operation::getType);
        LOG.info("Accepting offer {} with ops {}", offerId.getValue(), opTypes);

        Futures.getUnchecked(mesosFuture).send(Call
                .newBuilder().setFrameworkId(getFrameworkId()).setType(Call.Type.ACCEPT).setAccept(Call.Accept
                        .newBuilder().addOfferIds(offerId).addAllOperations(operations).setFilters(filter))
                .build());
    });

}

From source file:org.apache.aurora.scheduler.mesos.SchedulerDriverService.java

@Override
public void acceptOffers(Protos.OfferID offerId, Collection<Protos.Offer.Operation> operations,
        Protos.Filters filter) {// ww  w .  j  a v  a2s.  c o m
    ensureRunning();

    OfferID convertedOfferId = ProtosConversion.convert(offerId);
    Collection<Operation> convertedOperations = Collections2.transform(operations, ProtosConversion::convert);
    Filters convertedFilter = ProtosConversion.convert(filter);

    Futures.getUnchecked(driverFuture).acceptOffers(ImmutableList.of(convertedOfferId), convertedOperations,
            convertedFilter);
}