Example usage for com.google.common.util.concurrent SettableFuture create

List of usage examples for com.google.common.util.concurrent SettableFuture create

Introduction

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

Prototype

public static <V> SettableFuture<V> create() 

Source Link

Document

Creates a new SettableFuture that can be completed or cancelled by a later method call.

Usage

From source file:io.prestosql.execution.scheduler.ScaledWriterScheduler.java

@Override
public ScheduleResult schedule() {
    List<RemoteTask> writers = scheduleTasks(getNewTaskCount());

    future.set(null);/*from  w  ww.  ja v a 2 s . c  o  m*/
    future = SettableFuture.create();
    executor.schedule(() -> future.set(null), 200, MILLISECONDS);

    return new ScheduleResult(done.get(), writers, future, WRITER_SCALING, 0);
}

From source file:com.cloudera.impala.catalog.TableLoader.java

/**
 * Computes a replacement value for the Table based on an already-cached value.
 *
 * Returns (as a ListenableFuture) the future new value of the table.
 * The returned Future should not be null. Using a Future allows for a
 * synchronous or asynchronous implementation or reload().
 *///from   w ww . ja  v  a  2s .  co m
@Override
public ListenableFuture<Table> reload(String tableName, Table cachedValue) throws ImpalaException {
    SettableFuture<Table> newValue = SettableFuture.create();
    Table table = loadTable(tableName, cachedValue);
    newValue.set(table);
    return newValue;
}

From source file:co.cask.cdap.internal.app.deploy.InMemoryConfigurator.java

/**
 * Executes the <code>Application.configure</code> within the same JVM.
 * <p>// w ww .  ja  v  a  2  s  .  c o m
 * This method could be dangerous and should be used only in standalone mode.
 * </p>
 *
 * @return A instance of {@link ListenableFuture}.
 */
@Override
public ListenableFuture<ConfigResponse> config() {
    SettableFuture<ConfigResponse> result = SettableFuture.create();

    try {
        // Load the JAR using the JAR class load and load the manifest file.
        Manifest manifest = BundleJarUtil.getManifest(archive);
        Preconditions.checkArgument(manifest != null, "Failed to load manifest from %s", archive.toURI());
        Preconditions.checkArgument(manifest.getMainAttributes() != null,
                "Failed to load manifest attributes from %s", archive.toURI());

        String mainClassName = manifest.getMainAttributes().getValue(ManifestFields.MAIN_CLASS);
        Preconditions.checkArgument(mainClassName != null && !mainClassName.isEmpty(),
                "Main class attribute cannot be empty");

        File unpackedJarDir = Files.createTempDir();
        try (Archive archive = new Archive(BundleJarUtil.unpackProgramJar(this.archive, unpackedJarDir),
                mainClassName)) {
            Object appMain = archive.getMainClass().newInstance();
            if (!(appMain instanceof Application)) {
                throw new IllegalStateException(String.format("Application main class is of invalid type: %s",
                        appMain.getClass().getName()));
            }

            String bundleVersion = manifest.getMainAttributes().getValue(ManifestFields.BUNDLE_VERSION);

            Application app = (Application) appMain;
            ConfigResponse response = createResponse(app, bundleVersion);
            result.set(response);
        } finally {
            removeDir(unpackedJarDir);
        }

        return result;
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        return Futures.immediateFailedFuture(t);
    }
}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get PureCloud license definition.//from  w  ww  .ja  v  a2 s . c om
 * 
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<LicenseDefinition> getLicenseDefinitionAsync(GetLicenseDefinitionRequest request,
        final AsyncApiCallback<LicenseDefinition> callback) {
    try {
        final SettableFuture<LicenseDefinition> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<LicenseDefinition>() {
        }, new AsyncApiCallback<ApiResponse<LicenseDefinition>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseDefinition> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:io.prestosql.plugin.hive.util.AsyncQueue.java

private synchronized void signalIfFinishing() {
    if (finishing && borrowerCount == 0) {
        if (elements.size() == 0) {
            completeAsync(executor, notEmptySignal);
            notEmptySignal = SettableFuture.create();
        } else if (elements.size() >= targetQueueSize) {
            completeAsync(executor, notFullSignal);
            notFullSignal = SettableFuture.create();
        }//from   w w  w  .  ja  v a  2s .c  o  m
    }
}

From source file:com.facebook.buck.rules.CachingBuildEngine.java

@VisibleForTesting
public SettableFuture<BuildRuleSuccess> createFutureFor(BuildTarget buildTarget) {
    SettableFuture<BuildRuleSuccess> newFuture = SettableFuture.create();
    SettableFuture<BuildRuleSuccess> result = results.putIfAbsent(buildTarget, newFuture);
    return result == null ? newFuture : result;
}

From source file:com.facebook.buck.remoteexecution.grpc.GrpcRemoteExecutionClients.java

/** Reads a ByteStream onto the arg consumer. */
public static ListenableFuture<Void> readByteStream(String instanceName, Protocol.Digest digest,
        ByteStreamStub byteStreamStub, ThrowingConsumer<ByteString, IOException> dataConsumer) {
    String name = getReadResourceName(instanceName, digest);
    SettableFuture<Void> future = SettableFuture.create();
    byteStreamStub.read(ReadRequest.newBuilder().setResourceName(name).setReadLimit(0).setReadOffset(0).build(),
            new StreamObserver<ReadResponse>() {
                @Override/*from  w w w.  ja  v a 2  s.co m*/
                public void onNext(ReadResponse value) {
                    try {
                        dataConsumer.accept(value.getData());
                    } catch (IOException e) {
                        onError(e);
                    }
                }

                @Override
                public void onError(Throwable t) {
                    future.setException(t);
                }

                @Override
                public void onCompleted() {
                    future.set(null);
                }
            });
    return future;
}

From source file:com.spotify.futures.ConcurrencyLimiter.java

/**
 * the callable function will run as soon as the currently active set of
 * futures is less than the maxConcurrency limit.
 *
 * @param callable - a function that creates a future.
 * @returns a proxy future that completes with the future created by the
 *          input function./*from  ww w . j  a  va  2 s . c o  m*/
 *          This future will be immediately failed with
 *          {@link CapacityReachedException} if the soft queue size limit is exceeded.
 * @throws {@link NullPointerException} if callable is null
 */
public ListenableFuture<T> add(Callable<? extends ListenableFuture<T>> callable) {
    Preconditions.checkNotNull(callable);
    final SettableFuture<T> response = SettableFuture.create();
    final Job<T> job = new Job<T>(callable, response);
    if (queueSize.get() >= maxQueueSize) {
        final String message = "Queue size has reached capacity: " + maxQueueSize;
        return Futures.immediateFailedFuture(new CapacityReachedException(message));
    }
    queue.add(job);
    queueSize.incrementAndGet();
    pump();
    return response;
}

From source file:com.microsoft.services.sharepoint.ListClient.java

/**
 * Gets the list.//from w w w  .j  a va  2s  . co  m
 *
 * @param listName the list name
 * @return the list
 */
public ListenableFuture<SPList> getList(String listName) {
    final SettableFuture<SPList> result = SettableFuture.create();
    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')";
    getListUrl = String.format(getListUrl, urlEncode(listName));
    ListenableFuture<JSONObject> request = executeRequestJson(getListUrl, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            SPList list = new SPList();
            list.loadFromJson(json, true);
            result.set(list);
        }
    });

    return result;
}

From source file:org.opendaylight.lispflowmapping.netconf.impl.LispDeviceNetconfConnector.java

@Override
public Future<RpcResult<Void>> removeConnector(final RemoveConnectorInput input) {
    SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();

    if (verifyRemoveInput(input, futureResult) != true) {
        return futureResult;
    }/*from w  w w.  j a va 2  s. co  m*/

    return executor.submit(new RemoveConnector(input));

}