Codota Logo
JdkFutureAdapters
Code IndexAdd Codota to your IDE (free)

How to use
JdkFutureAdapters
in
com.google.common.util.concurrent

Best Java code snippets using com.google.common.util.concurrent.JdkFutureAdapters (Showing top 20 results out of 315)

  • Add the Codota plugin to your IDE and get smart completions
private void myMethod () {
StringBuilder s =
  • Codota Iconnew StringBuilder()
  • Codota Iconnew StringBuilder(32)
  • Codota IconString str;new StringBuilder(str)
  • Smart code suggestions by Codota
}
origin: google/guava

public void testListenInPoolThreadReturnsSameFuture() throws Exception {
 ListenableFuture<String> listenableFuture = immediateFuture(DATA1);
 assertSame(listenableFuture, listenInPoolThread(listenableFuture));
}
origin: spotify/helios

@Override
public void send(final String topic, final byte[] message) {
 final String combinedTopic = topicPrefix + topic;
 if (!healthchecker.isHealthy()) {
  log.warn("will not publish message to pubsub topic={} as the pubsub client "
       + "appears to be unhealthy", combinedTopic);
  return;
 }
 try {
  Futures.addCallback(
    JdkFutureAdapters.listenInPoolThread(
      pubsub.publishAsync(combinedTopic, Message.of(ByteArray.copyFrom(message)))),
    new FutureCallback<String>() {
     @Override
     public void onSuccess(@Nullable final String ackId) {
      log.debug("Sent an event to Google PubSub, topic: {}, ack: {}", combinedTopic, ackId);
     }
     @Override
     public void onFailure(final Throwable th) {
      log.warn("Unable to send an event to Google PubSub, topic: {}", combinedTopic, th);
     }
    }, MoreExecutors.directExecutor());
 } catch (Exception e) {
  log.warn("Failed to publish Google PubSub message, topic: {}", combinedTopic, e);
 }
}
origin: google/guava

public void testListenInPoolThreadRunsListenerAfterRuntimeException() throws Exception {
 RuntimeExceptionThrowingFuture<String> input = new RuntimeExceptionThrowingFuture<>();
 /*
  * The compiler recognizes that "input instanceof ListenableFuture" is
  * impossible. We want the test, though, in case that changes in the future,
  * so we use isInstance instead.
  */
 assertFalse(
   "Can't test the main listenInPoolThread path "
     + "if the input is already a ListenableFuture",
   ListenableFuture.class.isInstance(input));
 ListenableFuture<String> listenable = listenInPoolThread(input);
 /*
  * This will occur before the waiting get() in the
  * listenInPoolThread-spawned thread completes:
  */
 RecordingRunnable earlyListener = new RecordingRunnable();
 listenable.addListener(earlyListener, directExecutor());
 input.allowGetToComplete.countDown();
 // Now give the get() thread time to finish:
 assertTrue(earlyListener.wasRun.await(1, SECONDS));
 // Now test an additional addListener call, which will be run in-thread:
 RecordingRunnable lateListener = new RecordingRunnable();
 listenable.addListener(lateListener, directExecutor());
 assertTrue(lateListener.wasRun.await(1, SECONDS));
}
origin: google/guava

ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, executorService);
origin: google/guava

public void testListenInPoolThreadUsesGivenExecutor() throws Exception {
 ExecutorService executorService =
   newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).build());
 NonListenableSettableFuture<String> abstractFuture = NonListenableSettableFuture.create();
 ExecutorSpy spy = new ExecutorSpy(executorService);
 ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, spy);
 SingleCallListener singleCallListener = new SingleCallListener();
 singleCallListener.expectCall();
 assertFalse(spy.wasExecuted);
 assertFalse(singleCallListener.wasCalled());
 assertFalse(listenableFuture.isDone());
 listenableFuture.addListener(singleCallListener, executorService);
 abstractFuture.set(DATA1);
 assertEquals(DATA1, listenableFuture.get());
 singleCallListener.waitForCall();
 assertTrue(spy.wasExecuted);
 assertTrue(singleCallListener.wasCalled());
 assertTrue(listenableFuture.isDone());
}
origin: google/guava

public void testListenInPoolThreadIgnoresExecutorWhenDelegateIsDone() throws Exception {
 NonListenableSettableFuture<String> abstractFuture = NonListenableSettableFuture.create();
 abstractFuture.set(DATA1);
 ExecutorSpy spy = new ExecutorSpy(directExecutor());
 ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, spy);
 SingleCallListener singleCallListener = new SingleCallListener();
 singleCallListener.expectCall();
 assertFalse(spy.wasExecuted);
 assertFalse(singleCallListener.wasCalled());
 assertTrue(listenableFuture.isDone()); // We call AbstractFuture#set above.
 // #addListener() will run the listener immediately because the Future is
 // already finished (we explicitly set the result of it above).
 listenableFuture.addListener(singleCallListener, directExecutor());
 assertEquals(DATA1, listenableFuture.get());
 // 'spy' should have been ignored since 'abstractFuture' was done before
 // a listener was added.
 assertFalse(spy.wasExecuted);
 assertTrue(singleCallListener.wasCalled());
 assertTrue(listenableFuture.isDone());
}
origin: vbauer/caesar

/**
 * {@inheritDoc}
 */
@Override
public Object processResultFuture(final Future<?> future, final ExecutorService executor) {
  return JdkFutureAdapters.listenInPoolThread(future, executor);
}
origin: org.wisdom-framework/wisdom-executors

protected Task<V> submitted(Future<V> future) {
  this.submissionDate = System.currentTimeMillis();
  this.future = JdkFutureAdapters.listenInPoolThread(future);
  return this;
}
origin: org.wisdom-framework/wisdom-executors

protected ScheduledTask<V> submittedScheduledTask(ScheduledFuture delegate) {
  this.submissionDate = System.currentTimeMillis();
  this.scheduledFuture = delegate;
  this.future = JdkFutureAdapters.listenInPoolThread(delegate);
  return this;
}
origin: apache/incubator-wave

@Override
public ListenableFuture<String> asyncGet(final String url) {
 return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
  @Override
  public String call() throws RobotConnectionException {
   return get(url);
  }
 }));
}
origin: apache/incubator-wave

@Override
public ListenableFuture<String> asyncPostJson(final String url, final String body) {
 return JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<String>() {
  @Override
  public String call() throws RobotConnectionException {
   return postJson(url, body);
  }
 }));
}
origin: griddynamics/jagger

public ListenableFuture<State> start() {
  ListenableFuture<Nothing> runListener = JdkFutureAdapters.listenInPoolThread(executor.submit(new Callable<Nothing>() {
    @Override
    public Nothing call() {
      listener.onDistributionStarted(sessionId, taskId, task, remotes.keySet());
      return Nothing.INSTANCE;
    }
  }));
  return Futures.transform(runListener, new AsyncFunction<Nothing, State>() {
    @Override
    public ListenableFuture<State> apply(Nothing input) {
      return doStart();
    }
  });
}
origin: org.opendaylight.netide/shim

  public <E extends DataObject> void sendResponseToCore(Future<RpcResult<E>> switchReply,
      final ZeroMQBaseConnector coreConnector, final short ofVersion, final long xId, final long datapathId,
      final int moduleId) {

    Futures.addCallback(JdkFutureAdapters.listenInPoolThread(switchReply), new FutureCallback<RpcResult<E>>() {
      @Override
      public void onSuccess(RpcResult<E> rpcReply) {
        if (rpcReply.isSuccessful()) {
          E result = rpcReply.getResult();

          sendOpenFlowMessageToCore(coreConnector, result, ofVersion, xId, datapathId, moduleId);
        } else {
          for (RpcError rpcError : rpcReply.getErrors()) {
            LOG.info("SHIM RELAY: error in communication with switch: {}", rpcError.getMessage());
          }
        }
      }

      @Override
      public void onFailure(Throwable t) {
        LOG.info("SHIM RELAY: failure on communication with switch");
      }
    });
  }
}
origin: org.opendaylight.netide/shim

public void collectGetFeaturesOuput(Future<RpcResult<GetFeaturesOutput>> switchReply,
    final ConnectionAdapter connectionAdapter) {
  Futures.addCallback(JdkFutureAdapters.listenInPoolThread(switchReply),
      new FutureCallback<RpcResult<GetFeaturesOutput>>() {
        @Override
        public void onSuccess(RpcResult<GetFeaturesOutput> rpcFeatures) {
          if (rpcFeatures.isSuccessful()) {
            GetFeaturesOutput featureOutput = rpcFeatures.getResult();
            // Register Switch connection/DatapathId to registry
            connectionRegistry.registerConnectionAdapter(connectionAdapter, featureOutput);
            NodeUpdated nodeUpdated = nodeAdded(connectionAdapter);
            notificationProviderService.offerNotification(nodeUpdated);
          } else {
            // Handshake failed
            for (RpcError rpcError : rpcFeatures.getErrors()) {
              LOG.info("handshake - features failure [{}]: i:{} | m:{} | s:{}", rpcError.getInfo(),
                  rpcError.getMessage(), rpcError.getSeverity(), rpcError.getCause());
            }
          }
        }
        @Override
        public void onFailure(Throwable t) {
          LOG.info("getting feature failed seriously [addr:{}]: {}", connectionAdapter.getRemoteAddress(),
              t.getMessage());
        }
      });
}
origin: com.atlassian.util.concurrent/atlassian-util-concurrent

/**
 * Creates a promise from the given future.
 * 
 * @param future The future delegate for the new promise
 * @return The new promise
 */
public static <A> Promise<A> forFuture(Future<A> future) {
 return new Of<A>(JdkFutureAdapters.listenInPoolThread(future));
}
origin: com.github.avarabyeu/wills

/**
 * Creates Will object from JKS's {@link java.util.concurrent.Future}
 *
 * @param future JKS's Future
 * @param <A>    Type of Future and Will to be created
 * @return Created Will
 */
public static <A> Will<A> forFuture(Future<A> future) {
  return new Of<A>(JdkFutureAdapters.listenInPoolThread(future));
}
origin: org.opendaylight.openflowplugin/openflowplugin

/**
 * @param sessionContext switch session context
 * @return generationId from future RpcResult
 */
public static Future<BigInteger> readGenerationIdFromDevice(SessionContext sessionContext) {
  Future<RpcResult<RoleRequestOutput>> roleReply = sendRoleChangeRequest(sessionContext, OfpRole.NOCHANGE, BigInteger.ZERO);
  final SettableFuture<BigInteger> result = SettableFuture.create();
  Futures.addCallback(JdkFutureAdapters.listenInPoolThread(roleReply), new FutureCallback<RpcResult<RoleRequestOutput>>() {
    @Override
    public void onSuccess(RpcResult<RoleRequestOutput> input) {
      if(input != null && input.getResult() != null) {
        result.set(input.getResult().getGenerationId());
      }
    }
    @Override
    public void onFailure(Throwable t) {
      //TODO
    }
  });
  return result;
}
origin: jclouds/legacy-jclouds

@Override
public ListenableFuture<HttpResponse> submit(final HttpCommand command) {
 HTTPRequest nativeRequest = filterLogAndConvertRe(command.getCurrentRequest());
 ListenableFuture<HttpResponse> response = transform(
    listenInPoolThread(urlFetchService.fetchAsync(nativeRequest)), convertToJcloudsResponse);
 return transform(response, new Function<HttpResponse, HttpResponse>() {
   public HttpResponse apply(HttpResponse response) {
    return receiveResponse(command, response);
   }
 }, ioExecutor);
}
origin: org.opendaylight.groupbasedpolicy/sxp-mapper

  @Override
  public ListenableFuture<RpcResult<Void>> apply(final Optional<AddressEndpoint> input) throws Exception {
    final ListenableFuture<RpcResult<Void>> nextResult;
    if (input == null || !input.isPresent() || !isSameEpg(epInput, input.get())) {
      // invoke service
      return JdkFutureAdapters.listenInPoolThread(l3EndpointService.registerEndpoint(epInput));
    } else {
      final String existingL3EpMsg = String.format("address-endpoint for given key already exists: %s | %s",
          addressEndpoint.getContextId(), addressEndpoint.getAddress() );
      nextResult = Futures.immediateFailedFuture(new IllegalStateException(existingL3EpMsg));
    }
    return nextResult;
  }
});
origin: org.opendaylight.controller/sal-binding-broker-impl

private ListenableFuture<RpcResult<?>> invoke(final SchemaPath schemaPath, final DataObject input) {
  return JdkFutureAdapters.listenInPoolThread(invoker.invokeRpc(delegate, schemaPath.getLastComponent(), input));
}
com.google.common.util.concurrentJdkFutureAdapters

Javadoc

Utilities necessary for working with libraries that supply plain Future instances. Note that, whenever possible, it is strongly preferred to modify those libraries to return ListenableFuture directly.

Most used methods

  • listenInPoolThread
    Submits a blocking task for the given Future to provide ListenableFuturefunctionality.Warning: If th

Popular in Java

  • Reactive rest calls using spring rest template
  • setRequestProperty (URLConnection)
  • onCreateOptionsMenu (Activity)
  • getApplicationContext (Context)
  • FileReader (java.io)
    A specialized Reader that reads from a file in the file system. All read requests made by calling me
  • RandomAccessFile (java.io)
    Allows reading from and writing to a file in a random-access manner. This is different from the uni-
  • String (java.lang)
  • Locale (java.util)
    A Locale object represents a specific geographical, political, or cultural region. An operation that
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • Servlet (javax.servlet)
    Defines methods that all servlets must implement.A servlet is a small Java program that runs within
Codota Logo
  • Products

    Search for Java codeSearch for JavaScript codeEnterprise
  • IDE Plugins

    IntelliJ IDEAWebStormAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogCodota Academy Plugin user guide Terms of usePrivacy policyJava Code IndexJavascript Code Index
Get Codota for your IDE now