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.github.nethad.clustermeister.provisioning.ec2.AmazonNodeManager.java

public AmazonNodeManager(Configuration configuration) {
    this.configuration = configuration;
    loadConfiguration(configuration);//from w  w w  .  j av  a  2 s  .  c  o m

    this.executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    this.contextManager = new ContextManager(awsWebApiCredentials, executorService);
    this.ec2Facade = new AwsEc2Facade(contextManager);
    this.credentialsManager = new CredentialsManager(configuration, contextManager);
    this.amazonInstanceManager = new AmazonInstanceManager(contextManager, ec2Facade, profiles,
            artifactsToPreload);
}

From source file:org.opendaylight.sxp.core.threading.ThreadsWorker.java

/**
 * Custom ThreadsWorker constructor//from   w  ww . j a va  2s .co  m
 *
 * @param scheduledExecutorService ScheduledExecutorService which will be used for scheduling tasks like SXP timers
 * @param executorService          ExecutorService which will be used for executing tasks
 * @param executorServiceInbound   ExecutorService which will be used for executing inbound messaging behaviour
 * @param executorServiceOutbound  ExecutorService which will be used for executing outbound messaging behaviour
 */
public ThreadsWorker(ScheduledExecutorService scheduledExecutorService, ExecutorService executorService,
        ExecutorService executorServiceInbound, ExecutorService executorServiceOutbound) {
    for (WorkerType workerType : WorkerType.values()) {
        dequeMap.put(new QueueKey(workerType), new ArrayDeque<>());
    }
    this.scheduledExecutorService = MoreExecutors
            .listeningDecorator(Preconditions.checkNotNull(scheduledExecutorService));
    this.executorService = MoreExecutors.listeningDecorator(Preconditions.checkNotNull(executorService));
    this.executorServiceInbound = MoreExecutors
            .listeningDecorator(Preconditions.checkNotNull(executorServiceInbound));
    this.executorServiceOutbound = MoreExecutors
            .listeningDecorator(Preconditions.checkNotNull(executorServiceOutbound));
}

From source file:org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataTreeShard.java

private InMemoryDOMDataTreeShard(final DOMDataTreeIdentifier prefix, final Executor dataTreeChangeExecutor,
        final int maxDataChangeListenerQueueSize, final int submitQueueSize) {
    this.prefix = Preconditions.checkNotNull(prefix);

    final TreeType treeType = treeTypeFor(prefix.getDatastoreType());
    this.dataTree = InMemoryDataTreeFactory.getInstance().create(treeType, prefix.getRootIdentifier());

    this.shardChangePublisher = new InMemoryDOMDataTreeShardChangePublisher(dataTreeChangeExecutor,
            maxDataChangeListenerQueueSize, dataTree, prefix.getRootIdentifier(), childShards);

    final FastThreadPoolExecutor fte = new FastThreadPoolExecutor(1, submitQueueSize, "Shard[" + prefix + "]");
    fte.setRejectedExecutionHandler(CountingRejectedExecutionHandler.newCallerWaitsPolicy());
    this.executor = MoreExecutors.listeningDecorator(fte);
}

From source file:org.apache.druid.query.materializedview.DerivativeDataSourceManager.java

@LifecycleStart
public void start() {
    log.info("starting derivatives manager.");
    synchronized (lock) {
        if (started) {
            return;
        }//from   w w  w  . j  a  v  a  2s .c o m
        exec = MoreExecutors
                .listeningDecorator(Execs.scheduledSingleThreaded("DerivativeDataSourceManager-Exec-%d"));
        final Duration delay = config.getPollDuration().toStandardDuration();
        future = exec.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try {
                    updateDerivatives();
                } catch (Exception e) {
                    log.makeAlert(e, "uncaught exception in derivatives manager updating thread").emit();
                }
            }
        }, 0, delay.getMillis(), TimeUnit.MILLISECONDS);
        started = true;
    }
    log.info("Derivatives manager started.");
}

From source file:com.techcavern.pircbotz.MultiBotManager.java

/**
 * Create MultiBotManager with the specified thread pool. 
 * @param botPool A provided thread pool. 
 *//*from www .j  a  va  2  s .  c  o  m*/
public MultiBotManager(ExecutorService botPool) {
    checkNotNull(botPool, "Bot pool cannot be null");
    this.botPool = MoreExecutors.listeningDecorator(botPool);
    this.managerNumber = MANAGER_COUNT.getAndIncrement();
}

From source file:io.druid.client.CachingClusteredClient.java

@Inject
public CachingClusteredClient(QueryToolChestWarehouse warehouse, TimelineServerView serverView, Cache cache,
        @Smile ObjectMapper objectMapper, @BackgroundCaching ExecutorService backgroundExecutorService,
        CacheConfig cacheConfig) {/*from   w  ww  .  ja v a 2 s  . c  om*/
    this.warehouse = warehouse;
    this.serverView = serverView;
    this.cache = cache;
    this.objectMapper = objectMapper;
    this.cacheConfig = cacheConfig;
    this.backgroundExecutorService = MoreExecutors.listeningDecorator(backgroundExecutorService);

    serverView.registerSegmentCallback(Execs.singleThreaded("CCClient-ServerView-CB-%d"),
            new ServerView.BaseSegmentCallback() {
                @Override
                public ServerView.CallbackAction segmentRemoved(DruidServerMetadata server,
                        DataSegment segment) {
                    CachingClusteredClient.this.cache.close(segment.getIdentifier());
                    return ServerView.CallbackAction.CONTINUE;
                }
            });
}

From source file:org.opendaylight.faas.fabric.vxlan.VxlanFabricProvider.java

public VxlanFabricProvider(final DataBroker dataProvider, final RpcProviderRegistry rpcRegistry,
        final NotificationPublishService notificationService, final FabricRendererRegistry rendererRegistry,
        final List<GatewayMac> availableMacs) {
    this.dataBroker = dataProvider;
    this.rpcRegistry = rpcRegistry;
    this.rendererRegistry = rendererRegistry;
    this.availableMacs = availableMacs;

    executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());

    rendererRegistry.register(UnderlayerNetworkType.VXLAN, this);
}

From source file:de.softwareforge.kafka.LoadCommand.java

@Override
public void execute() throws Exception {
    Logging logging = Logging.initialize();
    logging.configure(new LoggingConfiguration());
    new LoggingMBean().setLevel("kafka", "ERROR");

    String tableNames = loaderOptions.tables;
    final Map<String, TpchTable<?>> allTables = ImmutableMap
            .copyOf(Maps.uniqueIndex(TpchTable.getTables(), new Function<TpchTable<?>, String>() {
                @Override//  w w  w. jav a2  s .  c  om
                public String apply(@Nonnull TpchTable<?> input) {
                    return input.getTableName();
                }
            }));

    List<String> tables;
    if (tableNames == null) {
        tables = ImmutableList.copyOf(allTables.keySet());
    } else {
        ImmutableList.Builder<String> builder = ImmutableList.builder();
        for (String tableName : Splitter.on(",").omitEmptyStrings().trimResults().split(tableNames)) {
            checkState(allTables.keySet().contains(tableName), "Table %s is unknown", tableName);
            builder.add(tableName);
        }
        tables = builder.build();
    }

    LOG.info("Processing tables: %s", tables);

    Properties props = new Properties();
    props.put("metadata.broker.list", loaderOptions.brokers);
    props.put("serializer.class", StringEncoder.class.getName());
    props.put("key.serializer.class", LongEncoder.class.getName());
    props.put("partitioner.class", LongPartitioner.class.getName());
    props.put("serializer.encoding", "UTF8");
    props.put("request.required.acks", "1");
    ProducerConfig producerConfig = new ProducerConfig(props);

    final ObjectMapper mapper = objectMapperProvider.get();
    mapper.enable(MapperFeature.AUTO_DETECT_GETTERS);

    final Producer<Long, String> producer = new Producer<>(producerConfig);

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

    ImmutableList.Builder<ListenableFuture<Long>> futureBuilder = ImmutableList.builder();

    for (final String table : tables) {
        ListenableFuture<Long> future = executor.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                TpchTable<?> tpchTable = allTables.get(table);
                LOG.info("Loading table '%s' into topic '%s%s'...", table, loaderOptions.prefix, table);
                long count = 0;

                for (List<? extends TpchEntity> partition : Iterables.partition(
                        tpchTable.createGenerator(loaderOptions.tpchType.getScaleFactor(), 1, 1), 100)) {
                    ImmutableList.Builder<KeyedMessage<Long, String>> builder = ImmutableList.builder();
                    for (TpchEntity o : partition) {
                        builder.add(new KeyedMessage<>(loaderOptions.prefix + table, count++,
                                mapper.writeValueAsString(o)));
                    }
                    producer.send(builder.build());
                }
                LOG.info("Generated %d rows for table '%s'.", count, table);
                return count;
            }
        });
        futureBuilder.add(future);
    }

    Futures.allAsList(futureBuilder.build()).get();
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.DAYS);
    producer.close();
}

From source file:com.voxelplugineering.voxelsniper.service.eventbus.AsyncEventBus.java

@Override
public void _init() {
    if (this.built) {
        return;//from ww w  . ja va  2  s  . c om
    }
    this.registry = new MapMaker().concurrencyLevel(4).makeMap();
    if (!this.explicitExecutor) {
        final String prefix = this.config.get("eventBusThreadPrefix", String.class)
                .or("AsyncEventBus-executor-");
        this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool(new ThreadFactory() {

            private final ThreadGroup group;
            private int count;

            {
                this.group = Thread.currentThread().getThreadGroup();
            }

            @Override
            public Thread newThread(Runnable r) {
                Thread thr = new Thread(this.group, r, prefix + this.count++);
                return thr;
            }
        }));
    }
    this.built = true;
}

From source file:com.facebook.nifty.ssl.PollingMultiFileWatcher.java

/**
 * Starts polling the watched files for changes.
 *
 * @param files a set of one or more files to watch for changes.
 * @param callback the callback to call with the set of files that changed since the last time.
 *///w  w  w.  j  a v  a 2  s . c o  m
@Override
public void start(Set<File> files, Consumer<Set<File>> callback) {
    if (isStarted()) {
        throw new IllegalStateException("start() should not be called more than once");
    }
    Set<File> filesCopy = ImmutableSet.copyOf(files);
    Preconditions.checkArgument(filesCopy.size() > 0, "must specify at least 1 file to watch for changes");
    this.callback = requireNonNull(callback);
    watchedFiles = filesCopy;
    executorService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1));
    future = executorService.scheduleAtFixedRate(this::scanFilesForChanges, initialDelay, interval, timeUnit);
}