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:com.navercorp.pinpoint.collector.dao.AutoFlusher.java

public void initialize() {
    if (CollectionUtils.isEmpty(cachedStatisticsDaoList)) {
        return;/*from w  w  w  . ja  v  a2s  . c om*/
    }

    ThreadFactory threadFactory = PinpointThreadFactory.createThreadFactory(this.getClass().getSimpleName());
    executor = Executors.newScheduledThreadPool(cachedStatisticsDaoList.size(), threadFactory);
    for (CachedStatisticsDao dao : cachedStatisticsDaoList) {
        executor.scheduleAtFixedRate(new Worker(dao), 0L, flushPeriod, TimeUnit.MILLISECONDS);
    }
    logger.info("Auto flusher initialized.");
}

From source file:org.apache.synapse.commons.throttle.core.ThrottleWindowReplicator.java

public ThrottleWindowReplicator() {

    String replicatorThreads = System.getProperty(WINDOW_REPLICATOR_POOL_SIZE);

    if (replicatorThreads != null) {
        replicatorPoolSize = Integer.parseInt(replicatorThreads);
    }/*w  ww  .  j av a  2 s . c  om*/

    if (log.isDebugEnabled()) {
        log.debug("Throttle window replicator pool size set to " + replicatorPoolSize);
    }

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(replicatorPoolSize,
            new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("Throttle window replicator - " + replicatorCount++);
                    return t;
                }
            });

    String windowReplicationFrequency = System.getProperty(WINDOW_REPLICATOR_FREQUENCY);
    if (windowReplicationFrequency == null) {
        windowReplicationFrequency = "50";
    }

    if (log.isDebugEnabled()) {
        log.debug("Throttling window replication frequency set to " + windowReplicationFrequency);
    }

    for (int i = 0; i < replicatorPoolSize; i++) {
        executor.scheduleAtFixedRate(new ReplicatorTask(), Integer.parseInt(windowReplicationFrequency),
                Integer.parseInt(windowReplicationFrequency), TimeUnit.MILLISECONDS);
    }
}

From source file:com.openteach.diamond.network.waverider.slave.failure.slave.DefaultMasterFailureMonitor.java

@Override
public boolean init() {
    // monitor scheduler
    monitorScheduler = Executors.newScheduledThreadPool(1,
            new WaveriderThreadFactory("Waverider-Monitor", null, false));
    return true;//from  w  w w  .ja  va 2s  .  co  m
}

From source file:com.quancheng.saluki.registry.consul.internal.ConsulClient.java

public ConsulClient(String host, int port) {
    client = new com.ecwid.consul.v1.ConsulClient(host, port);
    ttlScheduler = new TtlScheduler(client);
    scheduleRegistry = Executors.newScheduledThreadPool(1, new NamedThreadFactory("retryFailedTtl", true));
    scheduleRegistry.scheduleAtFixedRate(new Runnable() {

        @Override//from  w  w  w  . java2 s . co m
        public void run() {
            try {
                retryFailedTtl();
            } catch (Throwable e) {
                log.info("retry registry znode failed", e);
            }
        }
    }, ConsulConstants.HEARTBEAT_CIRCLE, ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS);
    log.info("ConsulEcwidClient init finish. client host:" + host + ", port:" + port);
}

From source file:natalia.dymnikova.util.ThreadPoolBeans.java

public ScheduledExecutorService commonPurposeScheduler0() {
    final ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(10,//from w w  w.j a v a2 s  .c o m
                    new ThreadFactoryBuilder().setNameFormat("common-purpose-scheduler-%03d").setDaemon(true)
                            .setUncaughtExceptionHandler(
                                    (t, e) -> log.debug("Uncaught exception in thread {}", t.getName(), e))
                            .build());

    log.debug("Constructed common purpose scheduler {}", scheduler);
    return scheduler;
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportServer.java

CopycatTransportServer(PartitionId partitionId, MessagingService messagingService) {
    this.partitionId = checkNotNull(partitionId);
    this.messagingService = checkNotNull(messagingService);
    this.messageSubject = String.format("onos-copycat-%s", partitionId);
    this.executorService = Executors.newScheduledThreadPool(
            Math.min(4, Runtime.getRuntime().availableProcessors()),
            new CatalystThreadFactory("copycat-server-p" + partitionId + "-%d"));
}

From source file:org.geowebcache.georss.GeoRSSPoller.java

/**
 * Upon instantiation, spawns out a thread after #{@code startUpDelaySecs} seconds that
 * periodically (at least every each layer's {@link GeoRSSFeedDefinition#getPollInterval() poll
 * interval} polls the layers feed for change sets and if changes are found spawns a reseed
 * process on the tiles affected by the change set.
 * /*  www .  j  a va2 s.  c o  m*/
 * @param seeder
 * @param startUpDelaySecs
 *            seconds to wait before start polling the layers
 */
public GeoRSSPoller(final TileBreeder seeder, final int startUpDelaySecs) {

    this.seeder = seeder;
    this.scheduledPolls = new ArrayList<PollDef>();
    this.scheduledTasks = new ArrayList<GeoRSSPollTask>();

    final int corePoolSize = 1;
    CustomizableThreadFactory tf = new CustomizableThreadFactory("GWC GeoRSS Poll Tasks-");
    tf.setDaemon(true);
    tf.setThreadPriority(Thread.MIN_PRIORITY + 1);
    schedulingPollExecutorService = Executors.newScheduledThreadPool(corePoolSize, tf);

    schedulingPollExecutorService.submit(new Runnable() {

        public void run() {
            logger.info("Initializing GeoRSS poller in a background job...");

            findEnabledPolls();

            if (pollCount() > 0) {

                final TimeUnit seconds = TimeUnit.SECONDS;
                for (PollDef poll : scheduledPolls) {
                    GeoRSSPollTask command = new GeoRSSPollTask(poll, seeder);
                    GeoRSSFeedDefinition pollDef = poll.getPollDef();
                    long period = pollDef.getPollInterval();

                    logger.info("Scheduling layer " + poll.getLayer().getName() + " to poll the GeoRSS feed "
                            + pollDef.getFeedUrl() + " every " + pollDef.getPollIntervalStr());

                    schedulingPollExecutorService.scheduleAtFixedRate(command, startUpDelaySecs, period,
                            seconds);

                    scheduledTasks.add(command);
                }
                logger.info("Will wait " + startUpDelaySecs + " seconds before launching the " + pollCount()
                        + " GeoRSS polls found");
            } else {
                logger.info("No enabled GeoRSS feeds found, poller will not run.");
            }
        }
    });
}

From source file:org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizationManager.java

/**
 * Initialize the RepositoryManager instance. The RepositoryManager must be initialized by
 * calling this method, before synchronizers can use it to schedule tasks.
 *
 * @param serverConfig Active Carbon ServerConfiguration
 *//*from w  w w  . ja  v  a2  s.  co m*/
public void init(ServerConfiguration serverConfig) {
    if (log.isDebugEnabled()) {
        log.debug("Initializing deployment synchronization manager");
    }

    int poolSize = DeploymentSynchronizerConstants.DEFAULT_POOL_SIZE;
    String value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.POOL_SIZE);
    if (value != null) {
        poolSize = Integer.parseInt(value);
    }

    repositoryTaskExecutor = Executors.newScheduledThreadPool(poolSize, new SimpleThreadFactory());
}

From source file:be.fgov.kszbcss.rhq.websphere.config.ConfigQueryServiceImpl.java

public ConfigQueryServiceImpl(String cacheName, File persistentFile, WebSphereServer server, String cell) {
    this.cell = cell;
    config = new CellConfiguration(server, cell);
    queryCache = new ConfigQueryCache(cacheName, config, persistentFile);
    epochPollExecutorService = Executors.newScheduledThreadPool(1,
            new NamedThreadFactory(cacheName + "-epoch-poll"));
    future = epochPollExecutorService.scheduleWithFixedDelay(this, 0, 30, TimeUnit.SECONDS);
    queryCache.start(2);//  w w  w  .  jav a  2s  .  c  o  m
    try {
        mbean = ManagementFactory.getPlatformMBeanServer().registerMBean(this, ObjectName
                .getInstance("rhq.websphere:type=ConfigQueryService,cell=" + cell + ",cacheName=" + cacheName));
    } catch (Throwable ex) {
        log.error("MBean registration failed", ex);
    }
}

From source file:org.apache.synapse.commons.throttle.core.ThrottleDistributedInstancesCleanupTask.java

public ThrottleDistributedInstancesCleanupTask() {
    throttleProperties = ThrottleServiceDataHolder.getInstance().getThrottleProperties();
    cleanUpPoolSize = Integer.parseInt(throttleProperties.getThrottleDistributedCleanupPoolSize());

    noOfTimestampObjectToBeCleared = Long.parseLong(throttleProperties.getThrottleDistributedCleanupAmount());

    distributedCleanupEnabled = Boolean
            .parseBoolean(throttleProperties.getThrottleDistributedCleanupTaskEnable());

    maxNonAssociatedCounterCountToClear = Integer
            .parseInt(throttleProperties.getMaxNonAssociatedCounterCleanupAmount());

    if (log.isDebugEnabled()) {
        log.debug("Throttle window replicator pool size set to " + cleanUpPoolSize);
    }//from  www . j  a  v a2 s  .c  o  m

    if (distributedCleanupEnabled) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(cleanUpPoolSize,
                new ThreadFactory() {

                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName("Throttle " + "Distributed Cleanup" + " Task");
                        return t;
                    }
                });

        String throttleFrequency = throttleProperties.getThrottleContextDistributedCleanupTaskFrequency();

        String distributedInstanceExpiry = throttleProperties
                .getThrottleContextDistributedExpiredInstanceTime();

        if (log.isDebugEnabled()) {
            log.debug("Throttling Cleanup Task Frequency set to " + throttleFrequency);
        }

        executor.scheduleAtFixedRate(new CleanupTask(), Integer.parseInt(throttleFrequency),
                Integer.parseInt(throttleFrequency), TimeUnit.MILLISECONDS);
        distributedInstanceExpiryMillis = Long.parseLong(distributedInstanceExpiry);
    }
}