Example usage for java.util.concurrent Executors newScheduledThreadPool

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

Introduction

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

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:org.codice.solr.factory.impl.SolrClientAdapter.java

private static ScheduledExecutorService createExecutor() throws NumberFormatException {
    return Executors.newScheduledThreadPool(
            NumberUtils.toInt(//from   w  w w  .  ja va  2s.  c  o  m
                    AccessController.doPrivileged((PrivilegedAction<String>) () -> System
                            .getProperty("org.codice.ddf.system.threadPoolSize")),
                    SolrClientAdapter.THREAD_POOL_DEFAULT_SIZE),
            StandardThreadFactoryBuilder.newThreadFactory("SolrClientAdapter"));
}

From source file:com.cloud.network.security.SecurityGroupManagerImpl.java

protected void createThreadPools() {
    _executorPool = Executors.newScheduledThreadPool(_numWorkerThreads, new NamedThreadFactory("NWGRP"));
    _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("NWGRP-Cleanup"));
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private boolean initCheckpointServer() {
    this.executor = Executors.newScheduledThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
        @Override//w w w  .  j a va 2s  .c  om
        public Thread newThread(Runnable r) {
            Thread thread = Executors.defaultThreadFactory().newThread(r);
            thread.setName(SQLReconfiguratorDB.class.getSimpleName() + myID);
            return thread;
        }
    });

    try {
        InetAddress addr = null;
        try {
            this.serverSock = new ServerSocket();
            // first try the configured address, else fall back to wildcard
            this.serverSock
                    .bind(new InetSocketAddress(addr = this.consistentNodeConfig.getBindAddress(myID), 0));
        } catch (IOException ioe) {
            log.info(this + " unable to open large checkpoint server socket on " + addr
                    + "; trying wildcard address instead");
            this.serverSock = new ServerSocket(0);
        }
        checkpointServerFuture = executor.submit(new CheckpointServer());
        return true;
    } catch (IOException e) {
        log.severe(this + " unable to open server socket for large checkpoint transfers");
        e.printStackTrace();
    }
    return false;
}

From source file:com.cloud.vm.UserVmManagerImpl.java

@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _name = name;/*w  w w . j  a v  a2s. c  om*/

    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    _configDao = locator.getDao(ConfigurationDao.class);
    if (_configDao == null) {
        throw new ConfigurationException("Unable to get the configuration dao.");
    }

    Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);

    _instance = configs.get("instance.name");
    if (_instance == null) {
        _instance = "DEFAULT";
    }

    String value = _configDao.getValue(Config.CreatePrivateTemplateFromVolumeWait.toString());
    _createprivatetemplatefromvolumewait = NumbersUtil.parseInt(value,
            Integer.parseInt(Config.CreatePrivateTemplateFromVolumeWait.getDefaultValue()));

    value = _configDao.getValue(Config.CreatePrivateTemplateFromSnapshotWait.toString());
    _createprivatetemplatefromsnapshotwait = NumbersUtil.parseInt(value,
            Integer.parseInt(Config.CreatePrivateTemplateFromSnapshotWait.getDefaultValue()));

    String workers = configs.get("expunge.workers");
    int wrks = NumbersUtil.parseInt(workers, 10);

    String time = configs.get("expunge.interval");
    _expungeInterval = NumbersUtil.parseInt(time, 86400);
    if (_expungeInterval < 600) {
        _expungeInterval = 600;
    }
    time = configs.get("expunge.delay");
    _expungeDelay = NumbersUtil.parseInt(time, _expungeInterval);
    if (_expungeDelay < 600) {
        _expungeDelay = 600;
    }
    _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("UserVm-Scavenger"));

    _itMgr.registerGuru(VirtualMachine.Type.User, this);

    VirtualMachine.State.getStateMachine()
            .registerListener(new UserVmStateListener(_usageEventDao, _networkDao, _nicDao));

    s_logger.info("User VM Manager is configured.");

    return true;
}

From source file:com.emc.storageos.systemservices.impl.upgrade.CoordinatorClientExt.java

/**
 * Initialization method./*  w ww  .ja  v a 2 s  . co  m*/
 * On standby site, start a thread to monitor local coordinatorsvc status
 * On active site, start a thread to monitor db quorum of each standby site
 */
public void start() {
    if (drUtil.isStandby()) {
        _log.info("Start monitoring local coordinatorsvc status on standby site");
        ScheduledExecutorService exe = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "CoordinatorsvcMonitor");
            }
        });
        // delay for a period of time to start the monitor. For DR switchover, we stop original active, then start new active. 
        // So the original active may not see the new active immediately after reboot
        exe.scheduleAtFixedRate(coordinatorSvcMonitor, 3 * COODINATOR_MONITORING_INTERVAL,
                COODINATOR_MONITORING_INTERVAL, TimeUnit.SECONDS);
    } else {
        _log.info("Start monitoring db quorum on all standby sites");
        ScheduledExecutorService exe = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "DbsvcQuorumMonitor");
            }
        });
        exe.scheduleAtFixedRate(new DbsvcQuorumMonitor(getMyNodeId(), _coordinator, dbCommonInfo), 0,
                DB_MONITORING_INTERVAL, TimeUnit.SECONDS);
    }
}

From source file:com.ebay.pulsar.sessionizer.impl.SessionizerProcessor.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void afterPropertiesSet() throws Exception {
    SessionizerConfigValidator validator = new SessionizerConfigValidator(config, config);
    lastConfig = config;/*  w  w w .ja v a2 s .c o m*/
    List<String> errors = validator.validate();
    if (!errors.isEmpty()) {
        throw new IllegalArgumentException("Config error: " + errors);
    }

    addedMBeans.add(Management.addBean(getBeanName(), this));
    addedMBeans.add(Management.addBean(errorManager));
    SessionizerEsperExceptionHandlerFactory.setErrorManager(errorManager);
    int threadNum = config.getThreadNum();
    int queueSize = config.getQueueSize();
    requestQueues = new BlockingQueue[threadNum];
    responseQueues = new BlockingQueue[threadNum];
    tasks = new SessionizerRunnable[threadNum];
    expirationInfo = new long[threadNum];
    eventCounters = new long[threadNum];

    addedMBeans.add(Management.addBean(config.getBeanName(), config));
    addedMBeans.add(Management.addBean(esperCounter));

    if (provider != null) {
        provider.init(this);
        provider.start();
    }

    warnThresHold = (int) (queueSize * 0.3);
    errorThresHold = (int) (queueSize * 0.8);
    pool = Executors.newFixedThreadPool(threadNum, new NameableThreadFactory("Sessionizer"));
    for (int i = 0; i < threadNum; i++) {
        requestQueues[i] = new SingleConsumerDisruptorQueue(queueSize);
        responseQueues[i] = new SingleConsumerDisruptorQueue(queueSize * 2);
        SessionizerRunnable runnable = new SessionizerRunnable(requestQueues[i], responseQueues[i], i);
        tasks[i] = runnable;
        pool.execute(runnable);
    }

    refreshConfig();
    int sleepCount = 120;
    for (int i = 0; i < threadNum; i++) {
        while (!tasks[i].intialized && !tasks[i].intializeFailed) {
            Thread.sleep(1000);
            sleepCount--;
            if (sleepCount == 0) {
                break;
            }
        }

        Thread.sleep(1000);

        if (sleepCount == 0 || tasks[i].intializeFailed) {
            throw new Exception("Fail to initlaize sessionizer");
        }
    }

    timer = Executors.newScheduledThreadPool(2, new NameableThreadFactory("SessionizerTimer"));
    timer.scheduleAtFixedRate(new LocalExpirationChecker(), 1000, 1000, TimeUnit.MILLISECONDS);
    timer.scheduleAtFixedRate(new LeakedRemoteSessionChecker(), 60000, 60000, TimeUnit.MILLISECONDS);
}

From source file:com.oneapm.base.SparkAggregation.java

private static void startZookeeperService(final FlowConstant flowConstant,
        final ZookeeperClient zookeeperClient) throws IOException {

    final Date startTime = new Date();
    ScheduledExecutorService service = Executors.newScheduledThreadPool(3, new ThreadFactory() {
        @Override/*from  ww  w  . j  a va2 s . co m*/
        public Thread newThread(Runnable r) {
            return new Thread(r, "Zookeeper-Writer-ThreadPool");
        }
    });

    final String zookeeper = Config.getConfig("alert.cnf").getProperty("kafaka.zoo", "127.0.0.1:2181");
    final String kafaka = Config.getConfig("alert.cnf").getProperty("kafaka.zoo", "127.0.0.1:9092");
    zookeeperClient.setLicense("/ni/license");
    zookeeperClient.createNode("/ni", "", true);
    zookeeperClient.createNode("/ni/process", "", true);
    zookeeperClient.createNode("/ni/process/Alarm", "", false);
    service.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                //?
                checkComponent();
                writeData();
            } catch (Exception e) {
                LOG.warn("zookeeper?:" + e.getMessage());
            }
        }

        //?
        private void checkComponent() {
            Socket clientSocket = null;
            try {
                String[] zookeeperInfo = zookeeper.split(":");
                clientSocket = new Socket(zookeeperInfo[0], Integer.valueOf(zookeeperInfo[1]));

                flowConstant.isZookeeperOkFlag = true;
                flowConstant.isKafkaOkFlag = true;
            } catch (Exception e) {
                flowConstant.isZookeeperOkFlag = false;
                flowConstant.isKafkaOkFlag = false;
            } finally {
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        LOG.warn("socket:" + e.getMessage());
                    }
                }
            }
            //                //kafka?
            //                try {
            //                    String[] kafakaInfo = kafaka.split(":");
            //                    clientSocket = new Socket(kafakaInfo[0], Integer.valueOf(kafakaInfo[1]));
            //
            //                    flowConstant.isKafkaOkFlag = true;
            //                } catch (Exception e) {
            //                    flowConstant.isKafkaOkFlag = false;
            //                } finally {
            //                    try {
            //                        clientSocket.close();
            //                    } catch (IOException e) {
            //                        LOG.warn("socket:" + e.getMessage());
            //                    }
            //                }
        }

        private void writeData() {
            Map<String, String> processInfoMap = new HashMap<String, String>();

            try {
                processInfoMap.put("host", String.valueOf(InetAddress.getLocalHost()));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            processInfoMap.put("setupLocation", System.getProperty("user.dir"));
            processInfoMap.put("startupTime", String.valueOf(startTime.getTime()));
            String licence = "no license";
            if (Integer.parseInt(zookeeperClient.getLicense().split("\n")[2].split("=")[1]) == 1) {
                licence = "ok";
            }
            processInfoMap.put("licence", licence);
            if (flowConstant.isEsOKFlag && flowConstant.isKafkaOkFlag && flowConstant.isZookeeperOkFlag) {
                processInfoMap.put("status", "ok");
            } else {
                List<String> components = new ArrayList<String>();
                if (!flowConstant.isEsOKFlag) {
                    components.add("es is not available!");
                }
                if (!flowConstant.isZookeeperOkFlag) {
                    components.add("zookeeper is not available!");
                }
                if (!flowConstant.isKafkaOkFlag) {
                    components.add("kafka is not available!");
                }

                processInfoMap.put("status", StringUtils.join(components, ";"));
            }
            String processInfo = JSON.toJSONString(processInfoMap);

            if (zookeeperClient.isExists("/ni/process/Alarm")) {
                zookeeperClient.writeData("/ni/process/Alarm", processInfo);
            } else {
                zookeeperClient.createNode("/ni", "", true);
                zookeeperClient.createNode("/ni/process", "", true);
                zookeeperClient.createNode("/ni/process/Alarm", "", false);
                zookeeperClient.writeData("/ni/process/Alarm", processInfo);
            }
        }

    }, 10, 60, TimeUnit.SECONDS);
}