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.gerrit.server.index.IndexModule.java

@Provides
@Singleton// www  . j a v  a2  s  .  c  o m
@IndexExecutor
ListeningScheduledExecutorService getIndexExecutor(@GerritServerConfig Config config, WorkQueue workQueue) {
    int threads = this.threads;
    if (threads <= 0) {
        threads = config.getInt("index", null, "threads", 0);
    }
    Executor executor;
    if (threads <= 0) {
        executor = workQueue.getDefaultQueue();
    } else {
        executor = workQueue.createQueue(threads, "index");
    }
    return MoreExecutors.listeningDecorator(executor);
}

From source file:com.chenchengzhi.windtalkers.server.WindServerConfiguration.java

@Provides
@Named("talkerExecutor")
private ListeningExecutorService getAgentsExecutor() {
    return MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}

From source file:org.spongepowered.lantern.world.storage.LanternWorldStorage.java

public LanternWorldStorage(Path world) {
    this.worldDir = world;
    this.regions = new RegionFileCache(world, ".mca");
    this.executor = MoreExecutors
            .listeningDecorator(LanternScheduler.getInstance().createAsyncExecutor(SpongeImpl.getPlugin()));
}

From source file:com.google.javascript.jscomp.PrebuildDependencyInfo.java

void prebuild(Iterable<CompilerInput> allInputs) {
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override//from  w  w w .j av a 2  s  .  c  o  m
        public Thread newThread(Runnable r) {
            Thread t = new Thread(null, r, "jscompiler-PrebuildDependencyInfo",
                    CompilerExecutor.COMPILER_STACK_SIZE);
            t.setDaemon(true); // Do not prevent the JVM from exiting.
            return t;
        }
    };
    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(numParallelThreads, numParallelThreads,
            Integer.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
    ListeningExecutorService executorService = MoreExecutors.listeningDecorator(poolExecutor);
    List<ListenableFuture<?>> futureList = new ArrayList<>(Iterables.size(allInputs));
    // TODO(moz): Support canceling all parsing on the first halting error
    for (final CompilerInput input : allInputs) {
        futureList.add(executorService.submit(new Runnable() {
            @Override
            public void run() {
                input.getDependencyInfo();
            }
        }));
    }

    poolExecutor.shutdown();
    try {
        Futures.allAsList(futureList).get();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.dirla.app.ws.rest.services.LogsRestService.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public DataTrafficResult addLogs(@RequestBody CheckTrafficRep checkTrafficRep) {

    List<LogData> results = null;
    long t1 = Calendar.getInstance().getTimeInMillis();

    final List<String> filesToUpload = checkTrafficRep.getFilesToUpload();

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));
    for (final String fileName : filesToUpload) {

        Callable<Integer> job = new Callable<Integer>() {

            @Override//w  ww  .  j a  va  2 s  . c  om
            public Integer call() throws Exception {
                List<LogData> lines = new ArrayList<LogData>();
                try {
                    lines.addAll(readFile(fileName));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Map<String, Long> data = new HashMap<String, Long>();

                for (LogData res : lines) {
                    String key = res.getDomain();
                    long value = res.getSize();
                    Long oldValue = data.get(key);
                    data.put(key, value + (oldValue != null ? oldValue : 0));
                }

                logsService.pushLogs("accessLogs." + fileName, data);

                return 0;
            }
        }; // create the job here
        ListenableFuture<Integer> completion = executor.submit(job);
        Futures.addCallback(completion, new FutureCallback<Integer>() {

            @Override
            public void onFailure(Throwable t) {
                // log error
            }

            @Override
            public void onSuccess(Integer result) {
                // do something with the result
            }

        });
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    UserDataTrafficResult userTrafficData = logsService.checkDataTraffic(checkTrafficRep.getClientAddress());

    long t2 = Calendar.getInstance().getTimeInMillis();

    DataTrafficResult dtr = new DataTrafficResult();
    dtr.setCheckTrafficRequest(checkTrafficRep);
    dtr.setTrafficValue(userTrafficData);
    dtr.setTime(t2 - t1);
    return dtr;
}

From source file:com.cloudera.oryx.kmeans.computation.local.WeightedPointsByFold.java

@Override
public List<List<WeightedRealVector>> call() throws InterruptedException, ExecutionException {
    Config config = ConfigUtils.getDefaultConfig();
    ClusterSettings cluster = ClusterSettings.create(config);
    KSketchIndex index = buildIndex(foldVecs, cluster);
    int pointsPerIteration = cluster.getSketchPoints();
    RandomGenerator random = RandomManager.getRandom();

    ListeningExecutorService exec = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(config.getInt("model.parallelism"),
                    new ThreadFactoryBuilder().setNameFormat("KSKETCH-%d").setDaemon(true).build()));
    for (int iter = 0; iter < cluster.getSketchIterations(); iter++) {
        log.info("Starting sketch iteration {}", iter + 1);
        List<ListenableFuture<Collection<RealVector>>> futures = Lists.newArrayList();
        for (int foldId = 0; foldId < foldVecs.size(); foldId++) {
            futures.add(exec/* www.j a  v a2 s. c  o  m*/
                    .submit(new SamplingRun(index, random, foldId, foldVecs.get(foldId), pointsPerIteration)));
        }
        // At the end of each iteration, gather up the sampled points to add to the index
        Future<List<Collection<RealVector>>> all = Futures.allAsList(futures);
        try {
            List<Collection<RealVector>> newSamples = all.get();
            for (int foldId = 0; foldId < foldVecs.size(); foldId++) {
                for (RealVector v : newSamples.get(foldId)) {
                    index.add(v, foldId);
                }
            }
        } catch (ExecutionException e) {
            ExecutorUtils.shutdownNowAndAwait(exec);
            all.cancel(true);
            throw e;
        }
        index.rebuildIndices();
    }

    List<ListenableFuture<List<WeightedRealVector>>> ret = Lists.newArrayList();
    for (int foldId = 0; foldId < foldVecs.size(); foldId++) {
        ret.add(exec.submit(new AssignmentRun(index, foldId, foldVecs.get(foldId))));
    }
    try {
        return Futures.allAsList(ret).get();
    } finally {
        ExecutorUtils.shutdownNowAndAwait(exec);
    }
}

From source file:com.eviware.loadui.util.execution.AbstractTestRunner.java

public AbstractTestRunner(ExecutorService executorService) {
    this.executorService = MoreExecutors.listeningDecorator(executorService);
}

From source file:org.springframework.integration.samples.helloworld.HelloService.java

public void doGuavaDownloadWithChainedThreads(final URL url) throws IOException {
    ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
    List<ListenableFuture<String>> calls = new ArrayList<ListenableFuture<String>>();
    while (calls.size() < 5) {
        com.google.common.util.concurrent.ListenableFuture<String> call = service
                .submit(new Callable<String>() {
                    @Override//from   w ww  .  j a  v a 2  s  .  c o m
                    public String call() throws Exception {
                        try (InputStream input = url.openStream()) {
                            return IOUtils.toString(input, StandardCharsets.UTF_8);
                        }
                    }
                });
        calls.add(call);
    }

    ListenableFuture<List<String>> goodCalls = Futures.successfulAsList(calls);
    Futures.addCallback(goodCalls, new FutureCallback<List<String>>() {
        @Override
        public void onSuccess(List<String> strings) {
            System.out.print("Successful call");
        }

        @Override
        public void onFailure(Throwable throwable) {
            System.err.println("Problems");
        }
    });

}

From source file:org.jclouds.chef.strategy.internal.ListEnvironmentsImpl.java

@Override
public Iterable<? extends Environment> execute(ExecutorService executor) {
    return this.execute(MoreExecutors.listeningDecorator(executor));
}

From source file:io.github.mywarp.mywarp.bukkit.SingleConnectionDataService.java

@Override
public ExecutorService getExecutorService() {
    if (executorService == null) {
        executorService = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    }//  w  w  w  .j  a v a 2  s  .c  om
    return executorService;
}