Guava ListenableFuture - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for Guava ListenableFuture class.

This code example shows how to use the following methods:get, isDone
   * 
   * @return true if the specified future has been resolved without throwing an exception or being 
   *     cancelled. 
   */ 
  public static boolean isSuccess(ListenableFuture<?> future) throws InterruptedException {
    if (!future.isDone()) {
      return false; 
    } 
 
    try { 
      // Try to get the future, but ignore (and preserve) the thread interrupted state. 
      // This should be fast because we know the future is already complete. 
      future.get();
      return true; 
    } catch (ExecutionException e) {
      // The computation threw an exception, so it did not complete successfully. 
      return false; 
    } catch (CancellationException e) {
      // The computation was cancelled, so it did not complete successfully. 
      return false; 
6
CodeRank
This code example shows how to use the following methods:get
   private static <T> Iterable<T> unwrap(Iterable<ListenableFuture<? extends T>> values) { 
      return transform(values, new Function<ListenableFuture<? extends T>, T>() { 
         @Override 
         public T apply(ListenableFuture<? extends T> from) { 
            try { 
               return from.get(); 
            } catch (InterruptedException e) { 
               propagate(e); 
            } catch (ExecutionException e) { 
               propagate(e); 
            } 
            return null; 
         } 
          
         @Override 
         public String toString() { 
            return "callGetOnFuture()"; 
         } 
      }); 
   } 
5
CodeRank
This code example shows how to use the following methods:isDone
    } 
 
    public void reserveMemory(long bytes)
    { 
        ListenableFuture<?> future = driverContext.reserveMemory(bytes);
        if (!future.isDone()) {
            SettableFuture<?> currentMemoryFuture = memoryFuture.get();
            while (currentMemoryFuture.isDone()) {
                SettableFuture<?> settableFuture = SettableFuture.create();
                // We can't replace one that's not done, because the task may be blocked on that future 
                if (memoryFuture.compareAndSet(currentMemoryFuture, settableFuture)) {
                    currentMemoryFuture = settableFuture;
                } 
                else { 
                    currentMemoryFuture = memoryFuture.get();
                } 
            } 
 
            SettableFuture<?> finalMemoryFuture = currentMemoryFuture;
            // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool 
4
CodeRank
This code example shows how to use the following methods:isDone
        { 
            @Override 
            public Boolean call()
                    throws Exception
            { 
                return driver.processFor(new Duration(1, TimeUnit.MILLISECONDS)).isDone();
            } 
        }); 
        brokenOperator.waitForLocked();
 
        driver.close();
        assertTrue(driver.isFinished());
 
        try { 
            driverProcessFor.get(1, TimeUnit.SECONDS);
            fail("Expected InterruptedException"); 
        } 
        catch (ExecutionException e) {
            checkArgument(getRootCause(e) instanceof InterruptedException, "Expected root cause exception to be an instance of InterruptedException");
        } 
4
CodeRank
This code example shows how to use the following methods:isDone
        assertTrue(sink.waitForWriting().isDone());
 
        // this will be ignored 
        sink.addPage(createPage(0));
        assertTrue(sink.isFinished());
        assertTrue(sink.waitForWriting().isDone());
    } 
 
    private static void assertExchangeTotalBufferedBytes(LocalExchange exchange, int pageCount)
    { 
        assertEquals(exchange.getBufferedBytes(), retainedSizeOfPages(pageCount));
    } 
 
    private static void assertExchangeTotalBufferedPages(LocalExchange exchange, int pageCount)
    { 
        assertEquals(exchange, retainedSizeOfPages(pageCount));
    } 
 
    private static Page createPage(int i)
    { 
4
CodeRank
This code example shows how to use the following methods:isDone
    } 
 
    private static ListenableFuture<?> enqueuePage(SharedOutputBuffer sharedBuffer, Page page, int partition)
    { 
        ListenableFuture<?> future = sharedBuffer.enqueue(partition, page);
        assertFalse(future.isDone());
        return future;
    } 
 
    private static void addPage(SharedOutputBuffer sharedBuffer, Page page)
    { 
        addPage(sharedBuffer, page, DEFAULT_PARTITION);
    } 
 
    private static void addPage(SharedOutputBuffer sharedBuffer, Page page, int partition)
    { 
        assertTrue(sharedBuffer.enqueue(partition, page).isDone());
    } 
 
    private static void assertQueueState( 
4
CodeRank
This code example shows how to use the following methods:isDone
        return state == State.RUNNING && blocked == NOT_BLOCKED;
    } 
 
    private void updateBlockedIfNecessary() 
    { 
        if (blocked != NOT_BLOCKED && blocked.isDone()) {
            blocked = NOT_BLOCKED;
        } 
    } 
 
    @Override 
    public void addInput(Page page)
    { 
        requireNonNull(page, "page is null");
        checkState(needsInput(), "Operator does not need input");
 
        Block[] blocks = new Block[inputChannels.size()];
        for (int outputChannel = 0; outputChannel < inputChannels.size(); outputChannel++) {
            blocks[outputChannel] = page.getBlock(inputChannels.get(outputChannel));
        } 
4
CodeRank
This code example shows how to use the following methods:isDone
    } 
 
    @Override 
    public boolean isFinished() 
    { 
        if (blocked != NOT_BLOCKED && blocked.isDone()) {
            blocked = NOT_BLOCKED;
        } 
 
        return finished && blocked == NOT_BLOCKED;
    } 
 
    @Override 
    public ListenableFuture<?> isBlocked()
    { 
        if (blocked != NOT_BLOCKED && blocked.isDone()) {
            blocked = NOT_BLOCKED;
        } 
        return blocked;
    } 
4
CodeRank
This code example shows how to use the following methods:isDone
This code example shows how to use the following methods:isDone
    } 
 
    @Override 
    public boolean needsInput() 
    { 
        return !isFinished() && isBlocked().isDone();
    } 
 
    @Override 
    public void addInput(Page page)
    { 
        requireNonNull(page, "page is null");
        page = pagePreprocessor.apply(page);
        sink.addPage(page);
        operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount());
    } 
 
    @Override 
    public Page getOutput()
    { 
4
CodeRank
This code example shows how to use the following methods:isDone
        return !finished && blocked == NOT_BLOCKED;
    } 
 
    private void updateBlockedIfNecessary() 
    { 
        if (blocked != NOT_BLOCKED && blocked.isDone()) {
            blocked = NOT_BLOCKED;
        } 
    } 
 
    @Override 
    public void addInput(Page page)
    { 
        requireNonNull(page, "page is null");
        checkState(blocked == NOT_BLOCKED, "output is already blocked");
        ListenableFuture<?> future = pageBuffer.add(page);
        if (!future.isDone()) {
            this.blocked = future;
        } 
        operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount());
4
CodeRank
This code example shows how to use the following methods:get
    Throwable expected = new GraphExecutionException(null, currentCallInfo, NO_CALLS);
 
    ListenableFuture<String> future = fallback.create(expected);
 
    try { 
      future.get();
      fail("expected an exception"); 
    } catch (ExecutionException e) {
      assertThat(e.getCause(), equalTo(expected));
    } 
  } 
 
  @Test
  public void shouldWrapGeneralException() throws Exception {
    Throwable expected = new RuntimeException("expected");
 
    ListenableFuture<String> future = fallback.create(expected);
 
    try { 
      future.get();
4
CodeRank
This code example shows how to use the following methods:get
        return tx;
    } 
 
    private static void assertCommitSuccessful(final ListenableFuture<Void> future)
            throws InterruptedException, ExecutionException {
        future.get();
    } 
 
    private static void assertTestContainerExists(final DOMDataReadTransaction readTx) throws InterruptedException,
            ExecutionException {
        ListenableFuture<Optional<NormalizedNode<?, ?>>> readFuture = readTx.read(OPERATIONAL, TestModel.TEST_PATH);
        Optional<NormalizedNode<?, ?>> readedData = readFuture.get();
        assertTrue(readedData.isPresent());
    } 
 
    private static void assertTestContainerWrite(final DOMDataReadWriteTransaction tx) throws InterruptedException,
            ExecutionException {
        tx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
        assertTestContainerExists(tx);
    } 
3
CodeRank
This code example shows how to use the following methods:addListener
This code example shows how to use the following methods:get
        return delegate.isDone();
    } 
 
    @Override 
    public V get() throws InterruptedException, ExecutionException {
        return delegate.get();
    } 
 
    @Override 
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return delegate.get(timeout, unit);
    } 
 
 
    private RuntimeException extractCauseFromExecutionException(ExecutionException e) {
        final Throwable cause = e.getCause();
        if (cause instanceof DriverException) {
            return ((DriverException) cause).copy();
        } else if (cause instanceof DriverInternalError) {
            return (DriverInternalError) cause;
4
CodeRank
This code example shows how to use the following methods:addListener
This code example shows how to use the following methods:get
      ExecutionException {
    // The first call to getPerUserWaveView() method causes the user's wavelets 
    // to be tracked. 
    provider.retrievePerUserWaveView(participant);
    ListenableFuture<Void> future = provider.onParticipantAdded(waveletName, participant);
    future.get();
  } 
 
  /** 
   * Factory method that creates the instance of {@link PerUserWaveViewHandler} to test. 
   */ 
  abstract protected PerUserWaveViewHandler createPerUserWaveViewHandler(); 
 
  /** 
   * Post update hook method that enables the subclasses to perform post update logic. 
   */ 
  abstract protected void postUpdateHook(); 
} 
4
CodeRank
This code example shows how to use the following methods:get
    return get(future, TIMEOUT_MILLIS);
  } 
 
  static <T> T get(final ListenableFuture<T> future, final long timeout)
      throws InterruptedException, ExecutionException, TimeoutException {
    return future.get(timeout, MILLISECONDS);
  } 
 
  static String getJobDescription(final Job job) {
    final String shortHash = job.getId().getHash().substring(0, 7);
    return String.format("%s (Job %s)", job.getImage(), shortHash);
  } 
 
  /** 
   * Undeploy the job from all specified hosts, and delete the job. Any failures will be ignored, 
   * and we will keep trying each host. A list of errors encountered along the way will be returned 
   * to the caller. 
   * @param client the HeliosClient to use 
   * @param job the job to undeploy and delete 
   * @param hosts the hosts to undeploy from 
3
CodeRank
This code example shows how to use the following methods:addListener
        return future.isCancelled();
    } 
 
    @Override 
    public void addListener(Runnable listener, Executor executor) {
        future.addListener(listener, executor);
    } 
 
    @Override 
    public boolean isDone() { 
        return future.isDone();
    } 
 
    @Override 
    public V get() throws InterruptedException, ExecutionException {
        return future.get();
    } 
 
    @Override 
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
4
CodeRank
This code example shows how to use the following methods:get
  public void assertSuccess(Object expectedData) throws Throwable {
    // Verify that the listener executed in a reasonable amount of time. 
    Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS));
 
    try { 
      Assert.assertEquals(expectedData, future.get());
    } catch (ExecutionException e) {
      throw e.getCause();
    } 
  } 
 
  /** 
   * Verify that the listener completes in a reasonable amount of time, and 
   * Asserts that the future throws an {@code ExecutableException} and that the 
   * cause of the {@code ExecutableException} is {@code expectedCause}. 
   */ 
  public void assertException(Throwable expectedCause) throws Exception {
    // Verify that the listener executed in a reasonable amount of time. 
    Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS));
 
4
CodeRank
This code example shows how to use the following methods:addListener
    } 
 
    // implements ListenableFuture<APIResponse> 
 
    public void addListener(Runnable listener, Executor executor) {
        this.apiResponse.addListener(listener, executor);
    } 
 
    // implements Future<APIResponse> 
 
    public boolean cancel(boolean mayInterruptIfRunning) {
        return this.apiResponse.cancel(mayInterruptIfRunning);
    } 
 
    public APIResponse get() throws ExecutionException, InterruptedException {
        return this.apiResponse.get();
    } 
 
    public APIResponse get(long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
        return this.apiResponse.get(timeout, unit);
4
CodeRank
This code example shows how to use the following methods:get
 
    @Override 
    protected Result check() {
        try { 
            ListenableFuture<Void> nopFuture = distributedStore.nop();
            nopFuture.get(TIMEOUT, TIMEOUT_TIME_UNIT);
            return Result.healthy("server is leader");
        } catch (TimeoutException e) {
            return Result.unhealthy(String.format("timed out after attempting to reach cluster for %d %s", TIMEOUT, TIMEOUT_TIME_UNIT));
        } catch (ExecutionException e) {
            if (e.getCause() instanceof NotLeaderException) {
                NotLeaderException leaderException = (NotLeaderException) e.getCause();
                String leader = leaderException.getLeader();
 
                if (leader != null) {
                    return Result.healthy(String.format("server not leader, but cluster has leader: %s", leader));
                } else { 
                    return Result.unhealthy("cluster does not have a leader");
                } 
            } else { 
3
CodeRank
This code example shows how to use the following methods:get
    assertTrue(execResults.get());
 
    // The result of restore is supposed to be a ListenableFuture<StatusReply>, which I can't cast 
    // to ErrorReply. Should get() throw an Exception instead? 
    try { 
      ErrorReply reply = (ErrorReply) restoreResults.get();
      fail("Should have thrown an exception"); 
    } catch (ExecutionException re) {
      Assert.assertTrue(re.getCause() instanceof RedisException);
    } catch (Exception e) {
      fail("Should have thrown an ExecutionException"); 
    } 
  } 
} 
4
CodeRank
This code example shows how to use the following methods:addListener
This code example shows how to use the following methods:addListener
    public void run() { 
        task.cancel();
    } 
 
    public static void addProgressListener(ListenableFuture<?> future, CommandSender sender, String message) {
        future.addListener(new FutureProgressListener(sender, message), MoreExecutors.sameThreadExecutor());
    } 
 
} 
4
CodeRank
This code example shows how to use the following methods:isDone
    } 
 
    @Override 
    public boolean needsInput() 
    { 
        return !isFinished() && isBlocked().isDone();
    } 
 
    @Override 
    public void addInput(Page page)
    { 
        checkNotNull(page, "page is null");
        checkState(!finished, "Already finished");
        inMemoryExchange.addPage(page);
        operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount());
    } 
 
    @Override 
    public Page getOutput() 
    { 
4
CodeRank
This code example shows how to use the following methods:get
        return domBroker;
    } 
 
    protected static final void assertCommit(final ListenableFuture<Void> commit) {
        try { 
            commit.get(500, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            throw new IllegalStateException(e);
        } 
    } 
 
 
} 
4
CodeRank
This code example shows how to use the following methods:get
        return domBroker;
    } 
 
    protected static final void assertCommit(final ListenableFuture<Void> commit) {
        try { 
            commit.get(500, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            throw new IllegalStateException(e);
        } 
    } 
 
 
} 
4
CodeRank
See Code Examples for Guava ListenableFuture Methods: