下面列出了怎么用com.google.common.util.concurrent.Futures的API类实例代码及写法,或者点击链接到github查看源代码。
private ListenableFuture<Void> getDependedOnModules() {
SettableFuture<Void> doneFuture = SettableFuture.create();
List<ListenableFuture<C5Module>> moduleFutures = new ArrayList<>();
moduleFutures.add(moduleInformationProvider.getModule(ModuleType.Log));
moduleFutures.add(moduleInformationProvider.getModule(ModuleType.Discovery));
ListenableFuture<List<C5Module>> compositeModulesFuture = Futures.allAsList(moduleFutures);
LOG.warn("ReplicatorService now waiting for module dependency on Log & Discovery");
C5Futures.addCallback(compositeModulesFuture,
(List<C5Module> modules) -> {
this.logModule = (LogModule) modules.get(0);
this.discoveryModule = (DiscoveryModule) modules.get(1);
doneFuture.set(null);
},
this::failModule, fiber);
return doneFuture;
}
private static String canDebug(
DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) {
// If we are debugging on a device, then the app needs to be debuggable
for (ListenableFuture<IDevice> future : deviceFutures.get()) {
if (!future.isDone()) {
// this is an emulator, and we assume that all emulators are debuggable
continue;
}
IDevice device = Futures.getUnchecked(future);
if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
return AndroidBundle.message(
"android.cannot.debug.noDebugPermissions", moduleName, device.getName());
}
}
return null;
}
/**
* Registers the client for template notifications
*
* @param pnsHandle PNS specific identifier
* @param templateName The template name
* @param template The template body
* @param callback The operation callback
* @deprecated use {@link #registerTemplate(String pnsHandle, String templateName, String template)} instead
*/
public void registerTemplate(String pnsHandle, String templateName, String template, final RegistrationCallback callback) {
ListenableFuture<Void> registerFuture = registerTemplate(pnsHandle, templateName, template);
Futures.addCallback(registerFuture, new FutureCallback<Void>() {
@Override
public void onFailure(Throwable exception) {
if (exception instanceof Exception) {
callback.onRegister((Exception) exception);
}
}
@Override
public void onSuccess(Void v) {
callback.onRegister(null);
}
}, MoreExecutors.directExecutor());
}
@Test
public void testConcurrentAddTag() throws Exception {
final int NUM_TASKS = Math.min(500 * Runtime.getRuntime().availableProcessors(), 1000);
List<ListenableFuture<?>> futures = Lists.newArrayList();
List<Integer> tags = Lists.newArrayList();
for (int i = 0; i < NUM_TASKS; i++) {
final int val = i;
ListenableFuture<?> future = executor.submit(new Runnable() {
@Override public void run() {
entity.tags().addTag(val);
}});
futures.add(future);
tags.add(val);
}
Futures.allAsList(futures).get();
Asserts.assertEqualsIgnoringOrder(entity.tags().getTags(), tags);
}
/**
* <p>Returns a future that wraps a list of all transactions that the given transaction depends on, recursively.
* Only transactions in peers memory pools are included; the recursion stops at transactions that are in the
* current best chain. So it doesn't make much sense to provide a tx that was already in the best chain and
* a precondition checks this.</p>
*
* <p>For example, if tx has 2 inputs that connect to transactions A and B, and transaction B is unconfirmed and
* has one input connecting to transaction C that is unconfirmed, and transaction C connects to transaction D
* that is in the chain, then this method will return either {B, C} or {C, B}. No ordering is guaranteed.</p>
*
* <p>This method is useful for apps that want to learn about how long an unconfirmed transaction might take
* to confirm, by checking for unexpectedly time locked transactions, unusually deep dependency trees or fee-paying
* transactions that depend on unconfirmed free transactions.</p>
*
* <p>Note that dependencies downloaded this way will not trigger the onTransaction method of event listeners.</p>
*/
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
log.info("{}: Downloading dependencies of {}", getAddress(), tx.getHashAsString());
final LinkedList<Transaction> results = new LinkedList<>();
// future will be invoked when the entire dependency tree has been walked and the results compiled.
final ListenableFuture<Object> future = downloadDependenciesInternal(vDownloadTxDependencyDepth, 0, tx,
new Object(), results);
final SettableFuture<List<Transaction>> resultFuture = SettableFuture.create();
Futures.addCallback(future, new FutureCallback<Object>() {
@Override
public void onSuccess(Object ignored) {
resultFuture.set(results);
}
@Override
public void onFailure(Throwable throwable) {
resultFuture.setException(throwable);
}
});
return resultFuture;
}
@Test
public void testFailureOnTimeout() throws Exception {
when(delegate.request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any()))
.thenReturn(Futures.<Response>immediateFailedFuture(new IOException()))
.thenReturn(Futures.<Response>immediateFuture(null));
when(clock.now()).thenReturn(new Instant(0)).thenReturn(new Instant(80000));
final ListenableFuture<Response> future = dispatcher.request(
new URI("http://example.com"), "GET", null, Collections.<String, List<String>>emptyMap());
// Verify the delegate was only called once if it failed on the first try and the deadline
// has passed before the second try was attempted.
verify(delegate, times(1)).request(any(URI.class), anyString(), any(byte[].class),
Matchers.<Map<String, List<String>>>any());
exception.expect(ExecutionException.class);
exception.expectCause(CoreMatchers.any(IOException.class));
future.get();
}
private ListenableFuture<HealthCheckResponse> ping() {
PlatformMessage msg = PlatformMessage.buildRequest(MessageBody.ping(), AlexaUtil.ADDRESS_BRIDGE, STATUS_SERVICE)
.withCorrelationId(IrisUUID.randomUUID().toString())
.create();
ListenableFuture<PlatformMessage> future = platSvc.request(
msg,
(pm) -> Objects.equals(msg.getCorrelationId(), pm.getCorrelationId()), config.getHealthCheckTimeoutSecs()
);
return Futures.transform(future, (Function<PlatformMessage, HealthCheckResponse>) input -> {
HealthCheckResponse response = new HealthCheckResponse();
response.setHealthy(true);
response.setDescription("The system is currently healthy");
return response;
}, MoreExecutors.directExecutor());
}
@Before
public void setUp() {
noConversionUploaderFactory =
(CommandEnvironment env) ->
new BuildEventArtifactUploader() {
@Override
public ListenableFuture<PathConverter> upload(Map<Path, LocalFile> files) {
return Futures.immediateFuture(PathConverter.NO_CONVERSION);
}
@Override
public boolean mayBeSlow() {
return false;
}
@Override
public void shutdown() {
// Intentionally left empty.
}
};
uploaderFactories =
new BuildEventArtifactUploaderFactoryMap.Builder()
.add("a", BuildEventArtifactUploaderFactory.LOCAL_FILES_UPLOADER_FACTORY)
.add("b", noConversionUploaderFactory)
.build();
}
@Test
public void indexItemAndContent_smallContentIsInlined() throws Exception {
ListenableFuture<Operation> expected = Futures.immediateFuture(new Operation());
when(batchingService.indexItem(any())).thenReturn(expected);
Item item = new Item().setName(GOOD_ID);
ByteArrayContent content = ByteArrayContent.fromString("text/plain", "Hello World.");
ListenableFuture<Operation> result = indexingService.indexItemAndContent(
item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);
verify(quotaServer).acquire(Operations.DEFAULT);
verify(batchingService).indexItem(indexCaptor.capture());
Items.Index updateRequest = indexCaptor.getValue();
assertEquals(ITEMS_RESOURCE_PREFIX + GOOD_ID, updateRequest.getName());
IndexItemRequest indexItemRequest = (IndexItemRequest) updateRequest.getJsonContent();
assertEquals(RequestMode.ASYNCHRONOUS.name(), indexItemRequest.getMode());
assertEquals(
new ItemContent()
.encodeInlineContent("Hello World.".getBytes(UTF_8))
.setContentFormat("TEXT"),
indexItemRequest.getItem().getContent());
assertThat(result, sameInstance(expected));
}
public void run() throws IOException {
Preconditions.checkState(inputManager != null, "InputManager must be configured");
if (maxTimeToWaitForReportMillis > 0) {
reporterExecutor = Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("ShuffleRunner {" + srcNameTrimmed + "}")
.build());
Future reporterFuture = reporterExecutor.submit(new ReporterCallable());
}
ListenableFuture<Void> runShuffleFuture = schedulerExecutor.submit(schedulerCallable);
Futures.addCallback(runShuffleFuture, new SchedulerFutureCallback(), GuavaShim.directExecutor());
// Shutdown this executor once this task, and the callback complete.
schedulerExecutor.shutdown();
}
/**
* Registers the client for push notification using device {@link Installation}
*
* @param installation device installation in Azure Notification Hub (https://msdn.microsoft.com/en-us/library/azure/mt621153.aspx)
* @return Future with registration information
*/
public ListenableFuture<Void> register(Installation installation) {
final SettableFuture<Void> resultFuture = SettableFuture.create();
ListenableFuture<Void> registerInternalFuture = createOrUpdateInstallation(installation);
Futures.addCallback(registerInternalFuture, new FutureCallback<Void>() {
@Override
public void onFailure(Throwable exception) {
resultFuture.setException(exception);
}
@Override
public void onSuccess(Void v) {
resultFuture.set(v);
}
}, MoreExecutors.directExecutor());
return resultFuture;
}
protected <T> Future<T> doInvoke(Callable<T> callable) {
try {
// always run after the current event finishes processing
// this gives more natural behavior from the event thread
SettableFuture<T> result = SettableFuture.create();
SwingUtilities.invokeLater(() -> {
if(result.isCancelled()) {
return;
}
try {
result.set(callable.call());
}
catch(Throwable t) {
logger.warn("Uncaught exception", t);
result.setException(t);
}
});
return result;
}
catch(Exception e) {
logger.warn("Uncaught exception", e);
return Futures.immediateFailedFuture(e);
}
}
@Test
public void schemaModuleShouldApplyProtoEnumArgs() {
Injector injector =
Guice.createInjector(
new SchemaModule() {
@Mutation("mutationMethodWithArgs")
ListenableFuture<GreetingsResponse> mutationMethod(
GreetingsRequest request, @Arg("myLanguage") Greetings.Languages myLanguage) {
return Futures.immediateFuture(
GreetingsResponse.newBuilder().setId(request.getId()).build());
}
});
SchemaBundle schemaBundle = SchemaBundle.combine(injector.getInstance(KEY));
assertThat(schemaBundle.mutationFields()).hasSize(1);
List<GraphQLArgument> arguments = schemaBundle.mutationFields().get(0).getArguments();
assertThat(arguments).hasSize(2);
assertThat(
arguments.stream()
.map(argument -> argument.getName())
.collect(ImmutableList.toImmutableList()))
.containsExactly("input", "myLanguage");
}
@Override
public void declineOffer(OfferID offerId, Filters filter) {
whenRegistered(() -> {
LOG.info("Declining offer {}", offerId.getValue());
Futures.getUnchecked(mesosFuture).send(
Call.newBuilder().setType(Call.Type.DECLINE)
.setFrameworkId(getFrameworkId())
.setDecline(
Call.Decline.newBuilder()
.setFilters(filter)
.addOfferIds(offerId))
.build()
);
});
}
@Override
public ListenableFuture<RpcResult<SubmitRemoveLspOutput>> submitRemoveLsp(final SubmitRemoveLspInput input) {
Preconditions.checkArgument(input.getNode() != null);
Preconditions.checkArgument(input.getName() != null);
final SubmitRemoveLspOutputBuilder b = new SubmitRemoveLspOutputBuilder();
b.setResult(AbstractInstructionExecutor.schedule(this.scheduler, new AbstractInstructionExecutor(input) {
@Override
protected ListenableFuture<OperationResult> invokeOperation() {
return TopologyProgramming.this.manager.removeLsp(input);
}
}));
final RpcResult<SubmitRemoveLspOutput> res = SuccessfulRpcResult.create(b.build());
return Futures.immediateFuture(res);
}
protected void watchCloseConfirmations() {
// When we see the close transaction get enough confirmations, we can just delete the record
// of this channel along with the refund tx from the wallet, because we're not going to need
// any of that any more.
final TransactionConfidence confidence = storedChannel.close.getConfidence();
int numConfirms = Context.get().getEventHorizon();
ListenableFuture<TransactionConfidence> future = confidence.getDepthFuture(numConfirms, Threading.SAME_THREAD);
Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
@Override
public void onSuccess(TransactionConfidence result) {
deleteChannelFromWallet();
}
@Override
public void onFailure(Throwable t) {
Throwables.propagate(t);
}
});
}
ListenableFuture<Void> start() {
ProgressiveBackoff progressiveBackoff = new ProgressiveBackoff(retrier::newBackoff);
AtomicLong committedOffset = new AtomicLong(0);
return Futures.transformAsync(
retrier.executeAsync(
() -> callAndQueryOnFailure(committedOffset, progressiveBackoff), progressiveBackoff),
(result) -> {
long committedSize = committedOffset.get();
long expected = chunker.getSize();
if (committedSize != expected) {
String message =
format(
"write incomplete: committed_size %d for %d total", committedSize, expected);
return Futures.immediateFailedFuture(new IOException(message));
}
return Futures.immediateFuture(null);
},
MoreExecutors.directExecutor());
}
@Test
public void testManuallySettingServiceStateIsNotOverwritten() throws Exception {
List<ListenableFuture<?>> futures = Lists.newArrayList();
for (int i = 0; i < 100; i++) {
ListenableFuture<Void> future = executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
TestEntity entity = app.addChild(EntitySpec.create(TestEntity.class));
entity.sensors().set(TestEntity.SERVICE_UP, true);
entity.sensors().set(TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
Thread.sleep(10);
assertEquals(entity.sensors().get(TestEntity.SERVICE_UP), Boolean.TRUE);
assertEquals(entity.sensors().get(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
Entities.unmanage(entity);
return null;
}});
futures.add(future);
}
Futures.allAsList(futures).get();
}
@Override
public void close() throws IOException {
UploadPartRequest uploadPartRequest = new UploadPartRequest()
.withBucketName(bucketName)
.withKey(key)
.withPartNumber(partNumber)
.withPartSize(outputStream.size())
.withUploadId(multipartUpload.getUploadId())
.withInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
etags.add(uploadPartResult.getPartETag());
ListenableFuture<List<Object>> future = Futures.allAsList(pendingUploads);
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
throw new IOException(e);
}
client.completeMultipartUpload(
new CompleteMultipartUploadRequest(
bucketName,
key,
multipartUpload.getUploadId(),
etags)
);
super.close();
}
@Test
public void testBinaryOperatorsDecimalBigint()
throws Exception
{
for (BigDecimal left : decimalLefts) {
for (Long right : longRights) {
assertExecute(generateExpression("%s = %s", left, right), BOOLEAN, left == null || right == null ? null : left.equals(new BigDecimal(right)));
assertExecute(generateExpression("%s <> %s", left, right), BOOLEAN, left == null || right == null ? null : !left.equals(new BigDecimal(right)));
assertExecute(generateExpression("%s > %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) > 0);
assertExecute(generateExpression("%s < %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) < 0);
assertExecute(generateExpression("%s >= %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) >= 0);
assertExecute(generateExpression("%s <= %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) <= 0);
assertExecute(generateExpression("nullif(%s, %s)", left, right), BigDecimal.class.cast(nullIf(left, right)));
assertExecute(generateExpression("%s is distinct from %s", left, right), BOOLEAN,
!Objects.equals(left, right == null ? null : new BigDecimal(right)));
// arithmetic operators are already tested in TestDecimalOperators
}
}
Futures.allAsList(futures).get();
}
public Future<SendResult> submit(final ProducerMessage<?> msg) {
SettableFuture<SendResult> future = SettableFuture.create();
if (msg.getCallback() != null) {
Futures.addCallback(future, new FutureCallback<SendResult>() {
@Override
public void onSuccess(SendResult result) {
msg.getCallback().onSuccess(result);
}
@Override
public void onFailure(Throwable t) {
msg.getCallback().onFailure(t);
}
}, m_callbackExecutor);
}
offer(msg, future);
return future;
}
private static <V, R> ListenableFuture<R> transformAsync(ListenableFuture<V> future,
Executor asyncExecutor, AsyncFunction<V, R> function) {
boolean inRollupThread = Session.isInRollupThread();
return Futures.transformAsync(future,
new AsyncFunction<V, R>() {
@Override
public ListenableFuture<R> apply(V input) throws Exception {
boolean priorInRollupThread = Session.isInRollupThread();
Session.setInRollupThread(inRollupThread);
try {
return function.apply(input);
} finally {
Session.setInRollupThread(priorInRollupThread);
}
}
},
// calls to Session.readAsync() inside of the function could block due to the
// per-thread concurrent limit, so this needs to be executed in its own thread, not
// in the cassandra driver thread that completes the last future which will block
// the cassandra driver thread pool
asyncExecutor);
}
/**
* A convenient variant of {@link #inCompletionOrder(Stream, int)} in which the user passes in a
* function and an executor to run it on.
*/
public static <U, V> Stream<V> inCompletionOrder(
Stream<U> arguments, Function<U, V> mapper, Executor executor, int maxParallelism) {
return inCompletionOrder(
arguments.map(x -> Futures.transform(Futures.immediateFuture(x), mapper::apply, executor)),
maxParallelism)
.map(Futures::getUnchecked);
}
static PendingAsyncTestContext fromTargetFuture(
ImmutableSet<ExecutorType> supportedExecutors,
ListenableFuture<TargetInfo> target,
PsiElement sourceElement,
ImmutableList<BlazeFlagsModification> blazeFlags,
@Nullable String description) {
Project project = sourceElement.getProject();
String buildSystem = Blaze.buildSystemName(project);
String progressMessage = String.format("Searching for %s target", buildSystem);
ListenableFuture<RunConfigurationContext> future =
Futures.transform(
target,
t -> {
if (t == null) {
return new FailedPendingRunConfiguration(
sourceElement, String.format("No %s target found.", buildSystem));
}
RunConfigurationContext context =
PendingWebTestContext.findWebTestContext(
project, supportedExecutors, t, sourceElement, blazeFlags, description);
return context != null
? context
: new KnownTargetTestContext(t, sourceElement, blazeFlags, description);
},
MoreExecutors.directExecutor());
return new PendingAsyncTestContext(
supportedExecutors, future, progressMessage, sourceElement, blazeFlags, description);
}
Future<Boolean> acquire() {
try {
log.debug("Acquiring lock for shard={}.", shard);
lockTaskCount.incrementAndGet();
return lockWorker.submit(acquirer());
} catch (RejectedExecutionException ex) {
log.warn(String.format("Rejected lock execution: active:%d queue:%d shard:%d", lockWorker.getActiveCount(), lockWorker.getQueue().size(), shard));
return Futures.immediateFuture(false);
}
}
private synchronized void executeCommand(final TransactionCommand command) {
ReadWriteTransaction transactionInFlight = null;
try {
final ReadWriteTransaction transaction = chain.newReadWriteTransaction();
transactionInFlight = transaction;
recordPendingTransaction(command, transaction);
command.execute(transaction);
Futures.addCallback(transaction.commit(), new FutureCallback<Object>() {
@Override
public void onSuccess(final Object result) {
forgetSuccessfulTransaction(transaction);
command.onSuccess();
}
@Override
public void onFailure(final Throwable throwable) {
command.onFailure(throwable);
// NOOP - handled by failure of transaction chain
}
}, MoreExecutors.directExecutor());
} catch (IllegalStateException e) {
if (transactionInFlight != null) {
// TODO: This method should distinguish exceptions on which the command should be
// retried from exceptions on which the command should NOT be retried.
// Then it should retry only the commands which should be retried, otherwise
// this method will retry commands which will never be successful forever.
offerFailedTransaction(transactionInFlight);
}
LOG.warn("Failed to process an update notification from OVS.", e);
}
}
private ListenableFuture<Unit> sendBatch() {
ImmutableList<BatchEntry> toSend = batch.build();
batch = ImmutableList.builder();
currentBatchSize = 0;
if (toSend.isEmpty()) {
return Futures.immediateFuture(Unit.UNIT);
} else {
return logMultiple(toSend);
}
}
@NotNull
@Override
public ListenableFuture<Void> remove(@NotNull final String client, @NotNull final String topic) {
try {
checkNotNull(client, "Client id must not be null");
checkNotNull(topic, "Topic must not be null");
final long timestamp = System.currentTimeMillis();
//parse topic for shared flag
final SharedSubscription sharedSubscription = sharedSubscriptionService.checkForSharedSubscription(topic);
if (sharedSubscription == null) {
//not a shared subscription
topicTree.removeSubscriber(client, topic, null);
} else {
if (sharedSubscription.getTopicFilter().isEmpty()) {
disconnectSharedSubscriberWithEmptyTopic(client);
return Futures.immediateFuture(null);
}
topicTree.removeSubscriber(client, sharedSubscription.getTopicFilter(), sharedSubscription.getShareName());
}
final ListenableFuture<Void> persistFuture = singleWriter.submit(client, (bucketIndex, queueBuckets, queueIndex) -> {
localPersistence.remove(client, topic, timestamp, bucketIndex);
return null;
});
//set future result when local persistence future and topic tree future return;
return Futures.whenAllComplete(persistFuture).call(() -> persistFuture.get(), MoreExecutors.directExecutor());
} catch (final Throwable throwable) {
return Futures.immediateFailedFuture(throwable);
}
}
public void finish() {
_open = false;
flushIf(true);
// Wait for writes to complete and check that they all succeeded
for (Future<OperationResult<Void>> future : _futures) {
Futures.getUnchecked(future);
}
}
@Override
public Future<Slice> getAsync(long bucketId, long time, Slice key)
{
long timeBucket = timeBucketAssigner.getTimeBucket(time);
if (timeBucket == -1) {
//time is expired so no point in looking further.
return Futures.immediateFuture(BucketedState.EXPIRED);
}
return getValueFromBucketAsync(bucketId, timeBucket, key);
}