Example usage for java.util.concurrent Executors newSingleThreadExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadExecutor.

Prototype

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed.

Usage

From source file:com.netflix.curator.framework.recipes.queue.QueueSharder.java

/**
 * @param client client/*from   w w w  .ja v  a2s  .com*/
 * @param queueAllocator allocator for new queues
 * @param queuePath path for the queues
 * @param leaderPath path for the leader that monitors queue sizes (must be different than queuePath)
 * @param policies sharding policies
 */
public QueueSharder(CuratorFramework client, QueueAllocator<U, T> queueAllocator, String queuePath,
        String leaderPath, QueueSharderPolicies policies) {
    this.client = client;
    this.queueAllocator = queueAllocator;
    this.queuePath = queuePath;
    this.policies = policies;
    leaderLatch = new LeaderLatch(client, leaderPath);
    service = Executors.newSingleThreadExecutor(policies.getThreadFactory());
}

From source file:net.brtly.monkeyboard.adb.DeviceManager.java

/**
 * Initialize the main DeviceManager instance. #init() can only be called
 * once, otherwise an IllegalStateException is thrown.
 * /*  w w  w  .ja va  2s  . com*/
 * @param eventBus
 */
public static void init(EventBus eventBus) {
    if (_isInit) {
        throw new IllegalStateException("DeviceManager already inited!");
    }
    INSTANCE = new DeviceManager(eventBus);

    LOG.debug("DeviceManager INIT");
    INSTANCE._deviceThreadPool = new DeviceThreadPool();
    INSTANCE._devices = new ConcurrentHashMap<String, DeviceState>();
    INSTANCE._chimpDevices = new ConcurrentHashMap<String, IChimpDevice>();
    INSTANCE._focusedDevice = null;

    // This mess makes a single threaded executor capable of executing
    // INSTANCE._workerExecutor =
    // MoreExecutors.listeningDecorator(Executors
    // .newSingleThreadExecutor(new ThreadFactoryBuilder()
    // .setNameFormat("DeviceManager-Worker-%d").build()));

    INSTANCE._workerExecutor = Executors
            .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("DeviceManager").build());
    // INSTANCE._workerExecutor = Executors
    // .newCachedThreadPool(new ThreadFactoryBuilder()
    // .setNameFormat("DeviceManager-worker-%d").build());
    INSTANCE._state = DeviceManagerState.STOPPED;
    _isInit = true;
}

From source file:com.google.android.apps.forscience.whistlepunk.metadata.CropHelper.java

public CropHelper(DataController dataController) {
    this(Executors.newSingleThreadExecutor(
            new ProcessPriorityThreadFactory(android.os.Process.THREAD_PRIORITY_BACKGROUND)), dataController);
}

From source file:io.druid.data.input.impl.PrefetchableTextFilesFirehoseFactory.java

private static ExecutorService createFetchExecutor() {
    return Executors
            .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("firehose_fetch_%d").build());
}

From source file:com.amazon.sqs.javamessaging.SQSMessageConsumer.java

SQSMessageConsumer(SQSConnection parentSQSConnection, SQSSession parentSQSSession,
        SQSSessionCallbackScheduler sqsSessionRunnable, SQSQueueDestination destination,
        Acknowledger acknowledger, NegativeAcknowledger negativeAcknowledger, ThreadFactory threadFactory,
        SQSMessageConsumerPrefetch sqsMessageConsumerPrefetch) {
    this.parentSQSSession = parentSQSSession;
    this.sqsDestination = destination;
    this.acknowledger = acknowledger;
    this.sqsSessionRunnable = sqsSessionRunnable;
    this.sqsMessageConsumerPrefetch = sqsMessageConsumerPrefetch;
    this.sqsMessageConsumerPrefetch.setMessageConsumer(this);
    this.negativeAcknowledger = negativeAcknowledger;

    prefetchExecutor = Executors.newSingleThreadExecutor(threadFactory);
    prefetchExecutor.execute(sqsMessageConsumerPrefetch);
}

From source file:com.xabber.android.data.connection.ConnectionThread.java

public ConnectionThread(final ConnectionItem connectionItem) {
    LogManager.i(this, "NEW connection thread " + connectionItem.getRealJid());

    this.connectionItem = connectionItem;
    executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override/* w  w w.  j ava2  s .  co m*/
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable,
                    "Connection thread for " + (connectionItem instanceof AccountItem
                            ? ((AccountItem) connectionItem).getAccount()
                            : connectionItem));
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setDaemon(true);
            return thread;
        }
    });
    ConnectionManager.getInstance().onConnection(this);
    ConnectionSettings connectionSettings = connectionItem.getConnectionSettings();
    protocol = connectionSettings.getProtocol();
    serverName = connectionSettings.getServerName();
    token = connectionSettings.getPassword();
    resource = connectionSettings.getResource();
    saslEnabled = connectionSettings.isSaslEnabled();
    tlsMode = connectionSettings.getTlsMode();
    compression = connectionSettings.useCompression();
    if (saslEnabled && protocol == AccountProtocol.gtalk)
        login = connectionSettings.getUserName() + "@" + connectionSettings.getServerName();
    else
        login = connectionSettings.getUserName();
    proxyType = connectionSettings.getProxyType();
    proxyHost = connectionSettings.getProxyHost();
    proxyPort = connectionSettings.getProxyPort();
    proxyUser = connectionSettings.getProxyUser();
    proxyPassword = connectionSettings.getProxyPassword();
    started = false;
}

From source file:io.gravitee.gateway.services.localregistry.LocalApiDefinitionRegistry.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        this.init();

        executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "registry-monitor"));
        executor.execute(() -> {//from   w w  w  .  j  a  v  a 2 s.  c o  m
            Path registry = Paths.get(registryPath);
            LOGGER.info("Start local registry monitor for directory {}", registry);

            try {
                WatchService watcher = registry.getFileSystem().newWatchService();
                registry.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                while (true) {
                    WatchKey key;
                    try {
                        key = watcher.take();
                    } catch (InterruptedException ex) {
                        return;
                    }

                    for (WatchEvent<?> event : key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();

                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path fileName = registry.resolve(ev.context().getFileName());

                        LOGGER.info("An event occurs for file {}: {}", fileName, kind.name());

                        if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null) {
                                if (apiManager.get(existingDefinition.getId()) != null) {
                                    apiManager.update(loadedDefinition);
                                } else {
                                    apiManager.undeploy(existingDefinition.getId());
                                    definitions.remove(fileName);
                                    apiManager.deploy(loadedDefinition);
                                    definitions.put(fileName, loadedDefinition);
                                }
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = apiManager.get(loadedDefinition.getId());
                            if (existingDefinition != null) {
                                apiManager.update(loadedDefinition);
                            } else {
                                apiManager.deploy(loadedDefinition);
                                definitions.put(fileName, loadedDefinition);
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null
                                    && apiManager.get(existingDefinition.getId()) != null) {
                                apiManager.undeploy(existingDefinition.getId());
                                definitions.remove(fileName);
                            }
                        }

                        boolean valid = key.reset();
                        if (!valid) {
                            break;
                        }
                    }
                }
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while looking for PI definitions from filesystem", ioe);
            }
        });
    }
}

From source file:com.asprise.imaging.core.Imaging.java

/** Use this executor service to make sure that all scanning related code is executed from the same thread. */
public static ExecutorService getDefaultExecutorServiceForScanning() {
    if (executorServiceForScanning == null) {
        synchronized (Imaging.class) {
            if (executorServiceForScanning == null) {
                executorServiceForScanning = Executors.newSingleThreadExecutor(new ThreadFactory() { // custom factory for user-friendly thread name
                    final AtomicInteger threadNumber = new AtomicInteger(1);
                    ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();

                    @Override/*from w  w  w  .jav  a2s  . c  o m*/
                    public Thread newThread(Runnable r) {
                        Thread thread = defaultThreadFactory.newThread(r);
                        thread.setName("scan" + (threadNumber.get() == 1 ? "" : "-" + threadNumber));
                        return thread;
                    }
                });
            }
        }
    }
    return executorServiceForScanning;
}

From source file:com.reactive.hzdfs.dll.AbstractFileSharingService.java

private void startHandlers() {
    threads = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override//from   w w  w.ja v  a  2  s . co m
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "FileSharingAgent.Worker");
            return t;
        }
    });

}

From source file:io.gravitee.gateway.service.ratelimit.AsyncRateLimitService.java

@Override
protected void doStart() throws Exception {
    super.doStart();

    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();/* ww  w. j a va 2 s.  c  o m*/
    DefaultListableBeanFactory parentBeanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext
            .getParent()).getBeanFactory();

    // Retrieve the current rate-limit repository implementation
    RateLimitRepository rateLimitRepository = parentBeanFactory.getBean(RateLimitRepository.class);
    LOGGER.debug("Rate-limit repository implementation is {}", rateLimitRepository.getClass().getName());

    if (enabled) {
        // Prepare caches
        RateLimitRepository aggregateCacheRateLimitRepository = new CachedRateLimitRepository(aggregateCache);
        RateLimitRepository localCacheRateLimitRepository = new CachedRateLimitRepository(localCache);

        // Prepare queue to flush data into the final repository implementation
        BlockingQueue<RateLimit> rateLimitsQueue = new BlockingArrayQueue<>(queueCapacity);

        LOGGER.debug("Register rate-limit repository asynchronous implementation {}",
                AsyncRateLimitRepository.class.getName());
        AsyncRateLimitRepository asyncRateLimitRepository = new AsyncRateLimitRepository();
        beanFactory.autowireBean(asyncRateLimitRepository);
        asyncRateLimitRepository.setLocalCacheRateLimitRepository(localCacheRateLimitRepository);
        asyncRateLimitRepository.setAggregateCacheRateLimitRepository(aggregateCacheRateLimitRepository);
        asyncRateLimitRepository.setRateLimitsQueue(rateLimitsQueue);

        LOGGER.info("Register the rate-limit service bridge for synchronous and asynchronous mode");
        DefaultRateLimitService rateLimitService = new DefaultRateLimitService();
        rateLimitService.setRateLimitRepository(rateLimitRepository);
        rateLimitService.setAsyncRateLimitRepository(asyncRateLimitRepository);
        parentBeanFactory.registerSingleton(RateLimitService.class.getName(), rateLimitService);

        // Prepare and start rate-limit poller
        rateLimitPollerExecutor = Executors
                .newSingleThreadScheduledExecutor(r -> new Thread(r, "rate-limit-poller"));
        RateLimitPoller rateLimitPoller = new RateLimitPoller();
        beanFactory.autowireBean(rateLimitPoller);
        rateLimitPoller.setRateLimitRepository(rateLimitRepository);
        rateLimitPoller.setAggregateCacheRateLimitRepository(aggregateCacheRateLimitRepository);

        LOGGER.info("Schedule rate-limit poller at fixed rate: {} {}", polling, TimeUnit.MILLISECONDS);
        rateLimitPollerExecutor.scheduleAtFixedRate(rateLimitPoller, 0L, polling, TimeUnit.MILLISECONDS);

        // Prepare and start rate-limit updater
        rateLimitUpdaterExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "rate-limit-updater"));
        RateLimitUpdater rateLimitUpdater = new RateLimitUpdater(rateLimitsQueue);
        beanFactory.autowireBean(rateLimitUpdater);
        rateLimitUpdater.setRateLimitRepository(rateLimitRepository);

        LOGGER.info("Start rate-limit updater");
        rateLimitUpdaterExecutor.submit(rateLimitUpdater);
    } else {
        // By disabling async and cached rate limiting, only the strict mode is allowed
        LOGGER.info("Register the rate-limit service bridge for strict mode only");
        DefaultRateLimitService rateLimitService = new DefaultRateLimitService();
        rateLimitService.setRateLimitRepository(rateLimitRepository);
        rateLimitService.setAsyncRateLimitRepository(rateLimitRepository);
        parentBeanFactory.registerSingleton(RateLimitService.class.getName(), rateLimitService);
    }
}