Example usage for com.google.common.util.concurrent ListeningExecutorService submit

List of usage examples for com.google.common.util.concurrent ListeningExecutorService submit

Introduction

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

Prototype

@Override
ListenableFuture<?> submit(Runnable task);

Source Link

Usage

From source file:com.google.devtools.build.android.GenerateRobolectricResourceSymbolsAction.java

public static void main(String[] args) throws Exception {

    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()));
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("robolectric_resources_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path generatedSources = Files.createDirectories(tmp.resolve("generated_resources"));
        // The reported availableProcessors may be higher than the actual resources
        // (on a shared system). On the other hand, a lot of the work is I/O, so it's not completely
        // CPU bound. As a compromise, divide by 2 the reported availableProcessors.
        int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
        ListeningExecutorService executorService = MoreExecutors
                .listeningDecorator(Executors.newFixedThreadPool(numThreads));
        try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) {

            logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

            final PlaceholderIdFieldInitializerBuilder robolectricIds = PlaceholderIdFieldInitializerBuilder
                    .from(aaptConfigOptions.androidJar);
            ParsedAndroidData.loadedFrom(options.data, executorService, AndroidDataDeserializer.create())
                    .writeResourcesTo(new AndroidResourceSymbolSink() {

                        @Override
                        public void acceptSimpleResource(ResourceType type, String name) {
                            robolectricIds.addSimpleResource(type, name);
                        }/*ww w  .  j  a  v  a2  s.  co  m*/

                        @Override
                        public void acceptPublicResource(ResourceType type, String name,
                                Optional<Integer> value) {
                            robolectricIds.addPublicResource(type, name, value);
                        }

                        @Override
                        public void acceptStyleableResource(FullyQualifiedName key,
                                Map<FullyQualifiedName, Boolean> attrs) {
                            robolectricIds.addStyleableResource(key, attrs);
                        }
                    });

            final RClassGenerator generator = RClassGenerator.with(generatedSources, robolectricIds.build(),
                    false);

            List<SymbolFileProvider> libraries = new ArrayList<>();
            for (DependencyAndroidData dataDep : options.data) {
                SymbolFileProvider library = dataDep.asSymbolFileProvider();
                libraries.add(library);
            }
            List<ListenableFuture<Boolean>> writeSymbolsTask = new ArrayList<>();
            for (final Entry<String, Collection<ListenableFuture<ResourceSymbols>>> librarySymbolEntry : ResourceSymbols
                    .loadFrom(libraries, executorService, null).asMap().entrySet()) {
                writeSymbolsTask
                        .add(executorService.submit(new WriteLibraryRClass(librarySymbolEntry, generator)));
            }
            FailedFutureAggregator.forIOExceptionsWithMessage("Errors writing symbols.")
                    .aggregateAndMaybeThrow(writeSymbolsTask);
        }

        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        AndroidResourceOutputs.createClassJar(generatedSources, options.classJarOutput);
        logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected", e);
        throw e;
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.Aapt2ResourceShrinkingAction.java

static Function<File, ListenableFuture<String>> manifestToPackageUsing(ListeningExecutorService executor) {
    return f -> executor.submit(() -> VariantConfiguration.getManifestPackage(f));
}

From source file:com.skcraft.plume.common.util.concurrent.Deferreds.java

/**
 * Make a new Deferred from the given callable, after submitting it to the
 * given executor./*w  w  w . ja  v  a2  s . co  m*/
 *
 * @param callable The callable
 * @param executor The default executor
 * @param <V> The type returned by the future
 * @return A new Deferred
 */
public static <V> Deferred<V> when(Callable<V> callable, ListeningExecutorService executor) {
    return new DeferredImpl<V>(executor.submit(callable), executor);
}

From source file:se.softhouse.common.testlib.Concurrently.java

/**
 * Returns a {@link ListenableFuture} running {@code callable} asynchronously. When this method
 * returns the {@link Callable#call()} may have been run or it may not. Call
 * {@link Future#get()} on the returned {@link Future} to get the result from the calculation.
 * The {@link Executor} running the returned {@link Future} is automatically shutdown when it's
 * done. If threads should be reused and performance is critical you should roll your own and
 * reuse the executor instead.//w  w  w  . ja va 2s  . c o m
 */
public static <T> ListenableFuture<T> run(Callable<T> callable) {
    final ListeningExecutorService executor = listeningDecorator(newSingleThreadExecutor());
    ListenableFuture<T> futureForCallable = executor.submit(callable);
    Futures.addCallback(futureForCallable, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            executor.shutdownNow();
        }

        @Override
        public void onFailure(Throwable t) {
            executor.shutdownNow();
        }
    });
    return futureForCallable;
}

From source file:com.google.devtools.build.android.resources.ResourceSymbols.java

/** Read the symbols from the provided symbol file. */
public static ListenableFuture<ResourceSymbols> load(Path primaryRTxt,
        ListeningExecutorService executorService) {
    return executorService.submit(new SymbolLoadingTask(primaryRTxt));
}

From source file:com.google.security.zynamics.binnavi.Gui.GraphWindows.Loader.CGraphOpener.java

public static void showGraphAndPerformCallBack(final IViewContainer container, final INaviView view,
        final CGraphWindow window, final Window parent, final FutureCallback<Boolean> callBack) {

    CWindowManager.instance().bringViewToFront(view);

    final ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

    final ListenableFuture<Boolean> loader = service
            .submit(generateViewLoader(view, container, window, parent));

    Futures.addCallback(loader, callBack);
}

From source file:org.excalibur.core.util.concurrent.Futures2.java

public static <V> List<ListenableFuture<V>> invokeAll(Iterable<Callable<V>> tasks,
        ListeningExecutorService executor) {
    List<ListenableFuture<V>> futures = Lists.newArrayList();

    for (Callable<V> task : tasks) {
        ListenableFuture<V> future = executor.submit(task);
        futures.add(future);/*  ww w .j  a v a 2  s  .c  o m*/
    }

    return futures;
}

From source file:com.facebook.buck.util.concurrent.MoreFutures.java

/**
 * Invoke multiple callables on the provided executor and wait for all to return successfully.
 * An exception is thrown (immediately) if any callable fails.
 * @param executorService Executor service.
 * @param callables Callables to call./*from ww  w .j a v  a2 s.co m*/
 * @return List of values from each invoked callable in order if all callables execute without
 *     throwing.
 * @throws ExecutionException If any callable throws an exception, the first of such is wrapped
 *     in an ExecutionException and thrown.  Access via
 *     {@link java.util.concurrent.ExecutionException#getCause()}}.
 */
public static <V> List<V> getAllUninterruptibly(ListeningExecutorService executorService,
        Iterable<Callable<V>> callables) throws ExecutionException {
    // Invoke.
    ImmutableList.Builder<ListenableFuture<V>> futures = ImmutableList.builder();
    for (Callable<V> callable : callables) {
        ListenableFuture<V> future = executorService.submit(callable);
        futures.add(future);
    }

    // Wait for completion.
    ListenableFuture<List<V>> allAsOne = Futures.allAsList(futures.build());
    return Uninterruptibles.getUninterruptibly(allAsOne);
}

From source file:com.facebook.buck.distributed.DistBuildFileHashes.java

private static ListenableFuture<ImmutableMap<BuildRule, RuleKey>> ruleKeyComputation(ActionGraph actionGraph,
        final LoadingCache<ProjectFilesystem, DefaultRuleKeyFactory> ruleKeyFactories,
        ListeningExecutorService executorService) {
    List<ListenableFuture<Map.Entry<BuildRule, RuleKey>>> ruleKeyEntries = new ArrayList<>();
    for (final BuildRule rule : actionGraph.getNodes()) {
        ruleKeyEntries.add(executorService.submit(() -> Maps.immutableEntry(rule,
                ruleKeyFactories.get(rule.getProjectFilesystem()).build(rule))));
    }/*from  w  ww  . j  a  v a2 s. c om*/
    ListenableFuture<List<Map.Entry<BuildRule, RuleKey>>> ruleKeyComputation = Futures
            .allAsList(ruleKeyEntries);
    return Futures.transform(ruleKeyComputation,
            new Function<List<Map.Entry<BuildRule, RuleKey>>, ImmutableMap<BuildRule, RuleKey>>() {
                @Override
                public ImmutableMap<BuildRule, RuleKey> apply(List<Map.Entry<BuildRule, RuleKey>> input) {
                    return ImmutableMap.copyOf(input);
                }
            }, executorService);
}

From source file:org.excalibur.core.util.concurrent.Futures2.java

public static <V> List<ListenableFuture<V>> invokeAll(Iterable<Callable<V>> tasks,
        ListeningExecutorService executor, FutureCallback<V>[] callbacks) {
    List<ListenableFuture<V>> futures = Lists.newArrayList();

    for (Callable<V> task : tasks) {
        ListenableFuture<V> future = executor.submit(task);
        futures.add(addCallbacks(future, callbacks));
    }//  w w w  . j  a  va  2  s .c  o  m

    return futures;
}