Example usage for com.google.common.util.concurrent MoreExecutors listeningDecorator

List of usage examples for com.google.common.util.concurrent MoreExecutors listeningDecorator

Introduction

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

Prototype

@GwtIncompatible("TODO")
public static ListeningScheduledExecutorService listeningDecorator(ScheduledExecutorService delegate) 

Source Link

Document

Creates a ScheduledExecutorService whose submit and invokeAll methods submit ListenableFutureTask instances to the given delegate executor.

Usage

From source file:com.google.cloud.bigtable.grpc.async.ResourceLimiterPerf.java

public static void main(String[] args) throws Exception {
    ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    try {//w  w  w  .  j  a  v  a  2s . c o  m
        for (int i = 0; i < 10; i++) {
            System.out.println("=======");
            test(pool);
        }
    } finally {
        pool.shutdownNow();
    }
}

From source file:org.immutables.mongo.fixture.ent.Ent.java

public static void main(String... args) throws UnknownHostException {
    MongoClient client = new MongoClient("localhost");
    RepositorySetup setup = RepositorySetup.builder().database(client.getDB("test"))
            .executor(MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()))
            .gson(new GsonBuilder().registerTypeAdapterFactory(new GsonAdaptersEnt()).create()).build();

    EntRepository repository = new EntRepository(setup);

    EntRepository.Criteria where = repository.criteria().uuid("8b7a881c-6ccb-4ada-8f6a-60cc99e6aa20")
            .actionIn("BAN", "IPBAN");

    Criteria or = where.expiresAbsent().or().with(where).expiresGreaterThan(TimeInstant.of(1467364749679L));

    System.out.println(or);/*  w ww.j a  v a  2  s.  co  m*/

    repository.find(or).fetchAll().getUnchecked();
}

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);
                        }/*from  w  w  w .  j ava  2s  . c om*/

                        @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:co.paralleluniverse.fibers.dropwizard.FiberManagedDataSource.java

public static ManagedDataSource wrap(ManagedDataSource ds, ExecutorService executor) {
    return new FiberManagedDataSource(ds, MoreExecutors.listeningDecorator(executor));
}

From source file:ch.vorburger.osgi.builder.internal.ExecutorServiceProvider.java

/**
 * See {@link Executors#newCachedThreadPool()}.
 *///from   ww  w. j av  a2s  .  c  om
public static ListeningExecutorService newCachedThreadPool(Logger logger, String poolName) {
    return MoreExecutors.listeningDecorator(Executors.unconfigurableExecutorService(
            Executors.newCachedThreadPool(newNamedThreadFactory(logger, poolName))));
}

From source file:com.spotify.sparkey.system.ReloadableReaderExample.java

private static void run() throws IOException, InterruptedException, ExecutionException {
    ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newSingleThreadExecutor());

    // create dummy log/index files, and load the reader from them
    final File logFile = new File("reloadabletest.spl");
    create(Sparkey.getIndexFile(logFile));
    final ReloadableSparkeyReader reader = ReloadableSparkeyReader.fromLogFile(logFile, executorService).get();

    // should be ignored (same file)
    reader.load(logFile);/* w w  w.  ja  v a 2 s  .  co  m*/

    // should load from second file now
    final File logFile2 = new File("reloadabletest2.spl");
    create(Sparkey.getIndexFile(logFile2));
    reader.load(logFile2);

    reader.close();
    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    System.out.println("Done!");
}

From source file:co.paralleluniverse.fibers.jdbc.FiberDataSource.java

/**
 * Wraps a JDBC {@link DataSource}./*w  ww  . j a  va2  s .  c  o  m*/
 * @param ds The {@link DataSource} to wrap.
 * @param executor The {@link ExecutorService} to use to actually execute JDBC operations.
 * @return 
 */
public static DataSource wrap(final DataSource ds, final ExecutorService executor) {
    return new FiberDataSource(ds, MoreExecutors.listeningDecorator(executor));
}

From source file:org.opendaylight.infrautils.utils.concurrent.Executors.java

/**
 * Creates a single thread executor with a {@link ThreadFactory} that uses
 * the provided prefix for its thread names and logs uncaught exceptions
 * with the specified {@link Logger}./*  ww  w .j av  a2 s  .c  om*/
 *
 * @param namePrefix Prefix for this executor thread names
 * @param logger Logger used to log uncaught exceptions
 * @return the newly created single-threaded Executor
 */
public static ListeningExecutorService newListeningSingleThreadExecutor(String namePrefix, Logger logger) {
    return MoreExecutors.listeningDecorator(newSingleThreadExecutor(namePrefix, logger));
}

From source file:ch.vorburger.osgi.builder.internal.ExecutorServiceProvider.java

/**
 * See {@link Executors#newFixedThreadPool(int)} and {@link Executors#newSingleThreadExecutor()}.
 *///from w  ww  .j a  v  a 2 s.  c  o  m
public static ListeningExecutorService newFixedThreadPool(Logger logger, int nThreads, String poolName) {
    if (nThreads != 1) {
        return MoreExecutors.listeningDecorator(Executors.unconfigurableExecutorService(
                Executors.newFixedThreadPool(nThreads, newNamedThreadFactory(logger, poolName))));
    } else {
        return MoreExecutors.listeningDecorator(Executors.unconfigurableExecutorService(
                Executors.newSingleThreadExecutor(newNamedThreadFactory(logger, poolName))));
    }
}

From source file:com.github.tempora.concurrent.BackgroundTaskExecutor.java

private static <T> void execute(final BackgroundTask<T> task, boolean wait) {
    final ListeningExecutorService service = MoreExecutors.listeningDecorator(
            wait ? MoreExecutors.sameThreadExecutor() : Executors.newSingleThreadExecutor());
    try {/*from ww  w  .j a v  a 2  s. c o m*/
        if (task instanceof LifecycleAware) {
            ((LifecycleAware) task).beforeCall();
        }
        final ListenableFuture<T> resultFuture = service.submit(task);
        task.relatedFuture = resultFuture;
        Futures.addCallback(resultFuture, task);
        if (task instanceof LifecycleAware) {
            Futures.addCallback(resultFuture, new FutureCallback<T>() {
                @Override
                public void onSuccess(T result) {
                    ((LifecycleAware) task).afterCall();
                }

                @Override
                public void onFailure(Throwable t) {
                    ((LifecycleAware) task).afterCall();
                }
            });
        }
        if (wait) {
            Futures.getUnchecked(resultFuture);
        }
    } finally {
        service.shutdown();
    }
}