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.openspaces.admin.internal.admin.DefaultAdmin.java

private ScheduledThreadPoolExecutor createScheduledThreadPoolExecutor(String threadName, int numberOfThreads) {
    final ClassLoader correctClassLoader = Thread.currentThread().getContextClassLoader();
    ScheduledThreadPoolExecutor executorService = (ScheduledThreadPoolExecutor) Executors
            .newScheduledThreadPool(numberOfThreads, new GSThreadFactory(threadName, useDaemonThreads) {
                @Override/* www  .  j a v  a 2s  .  c  o m*/
                public Thread newThread(Runnable r) {
                    Thread thread = super.newThread(r);
                    thread.setContextClassLoader(correctClassLoader);
                    return thread;
                }
            });
    return executorService;
}

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

@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    String enabled = _configDao.getValue("direct.attach.network.groups.enabled");
    if ("true".equalsIgnoreCase(enabled)) {
        _enabled = true;/*from ww  w.  j  ava  2 s.c  om*/
    }
    if (!_enabled) {
        return false;
    }
    _answerListener = new NetworkGroupListener(this, _agentMgr, _workDao);
    _agentMgr.registerForHostEvents(_answerListener, true, true, true);

    _serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId();
    _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("NWGRP"));
    _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("NWGRP-Cleanup"));

    return true;
}

From source file:com.cloud.storage.StorageManagerImpl.java

@Override
public boolean configure(String name, Map<String, Object> params) {
    Map<String, String> configs = _configDao.getConfiguration("management-server", params);

    _storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"),
            1800);/*from   w  w w.j a v a  2s .c o  m*/
    s_logger.info("pool.acquisition.wait.seconds is configured as " + _storagePoolAcquisitionWaitSeconds
            + " seconds");

    _agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _storagePoolDao, _dataStoreProviderMgr), true,
            false, true);

    s_logger.info("Storage cleanup enabled: " + StorageCleanupEnabled.value() + ", interval: "
            + StorageCleanupInterval.value() + ", delay: " + StorageCleanupDelay.value()
            + ", template cleanup enabled: " + TemplateCleanupEnabled.value());

    String cleanupInterval = configs.get("extract.url.cleanup.interval");
    _downloadUrlCleanupInterval = NumbersUtil.parseInt(cleanupInterval, 7200);

    String urlExpirationInterval = configs.get("extract.url.expiration.interval");
    _downloadUrlExpirationInterval = NumbersUtil.parseInt(urlExpirationInterval, 14400);

    String workers = configs.get("expunge.workers");
    int wrks = NumbersUtil.parseInt(workers, 10);
    _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("StorageManager-Scavenger"));

    _agentMgr.registerForHostEvents(ComponentContext.inject(LocalStoragePoolListener.class), true, false,
            false);

    _serverId = _msServer.getId();

    UpHostsInPoolSearch = _storagePoolHostDao.createSearchBuilder(Long.class);
    UpHostsInPoolSearch.selectFields(UpHostsInPoolSearch.entity().getHostId());
    SearchBuilder<HostVO> hostSearch = _hostDao.createSearchBuilder();
    hostSearch.and("status", hostSearch.entity().getStatus(), Op.EQ);
    hostSearch.and("resourceState", hostSearch.entity().getResourceState(), Op.EQ);
    UpHostsInPoolSearch.join("hosts", hostSearch, hostSearch.entity().getId(),
            UpHostsInPoolSearch.entity().getHostId(), JoinType.INNER);
    UpHostsInPoolSearch.and("pool", UpHostsInPoolSearch.entity().getPoolId(), Op.EQ);
    UpHostsInPoolSearch.done();

    StoragePoolSearch = _vmInstanceDao.createSearchBuilder();

    SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder();
    volumeSearch.and("volumeType", volumeSearch.entity().getVolumeType(), SearchCriteria.Op.EQ);
    volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ);
    volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ);
    StoragePoolSearch.join("vmVolume", volumeSearch, volumeSearch.entity().getInstanceId(),
            StoragePoolSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    StoragePoolSearch.done();

    LocalStorageSearch = _storagePoolDao.createSearchBuilder();
    SearchBuilder<StoragePoolHostVO> storageHostSearch = _storagePoolHostDao.createSearchBuilder();
    storageHostSearch.and("hostId", storageHostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
    LocalStorageSearch.join("poolHost", storageHostSearch, storageHostSearch.entity().getPoolId(),
            LocalStorageSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    LocalStorageSearch.and("type", LocalStorageSearch.entity().getPoolType(), SearchCriteria.Op.IN);
    LocalStorageSearch.done();

    Volume.State.getStateMachine().registerListener(new VolumeStateListener(_configDao, _vmInstanceDao));

    return true;
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldNotShutdownExecutorServicesSuppliedToGremlinExecutor() throws Exception {
    final ScheduledExecutorService service = Executors.newScheduledThreadPool(4, testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().executorService(service)
            .scheduledExecutorService(service).create();

    gremlinExecutor.close();/*from  w w  w .ja  v  a 2 s .c  o  m*/
    assertFalse(service.isShutdown());
    service.shutdown();
    service.awaitTermination(30000, TimeUnit.MILLISECONDS);
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldGetExecutorService() throws Exception {
    final ScheduledExecutorService service = Executors.newScheduledThreadPool(4, testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().executorService(service)
            .scheduledExecutorService(service).create();

    assertSame(service, gremlinExecutor.getExecutorService());
    gremlinExecutor.close();/*from  ww  w  .j a va2s  . c  o  m*/
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

public void scheduleSyncTask(RepositoryInformation repoInformation, boolean autoCheckout, boolean autoCommit,
        long delay) {

    int tenantId = Integer.parseInt(repoInformation.getTenantId());

    RepositoryContext repoCtxt = tenantToRepoContextMap.get(tenantId);
    if (repoCtxt == null) {
        log.error("Unable to schedule artifact sync task, repositoryContext null for tenant " + tenantId);
        return;//  w  ww  . j a v  a 2s .  com
    }

    if (repoCtxt.getArtifactSyncSchedular() == null) {
        synchronized (repoCtxt) {
            if (repoCtxt.getArtifactSyncSchedular() == null) {
                // create a new ScheduledExecutorService instance
                final ScheduledExecutorService artifactSyncScheduler = Executors.newScheduledThreadPool(1,
                        new ArtifactSyncTaskThreadFactory(repoCtxt.getGitLocalRepoPath()));

                // schedule at the given interval
                artifactSyncScheduler.scheduleAtFixedRate(
                        new ArtifactSyncTask(repoInformation, autoCheckout, autoCommit), delay, delay,
                        TimeUnit.SECONDS);
                // cache
                repoCtxt.setArtifactSyncSchedular(artifactSyncScheduler);

                log.info("Scheduled Artifact Synchronization Task for path " + repoCtxt.getGitLocalRepoPath());

            } else {
                log.info("Artifact Synchronization Task for path " + repoCtxt.getGitLocalRepoPath()
                        + " already scheduled");
            }
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldGetScheduledExecutorService() throws Exception {
    final ScheduledExecutorService service = Executors.newScheduledThreadPool(4, testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().executorService(service)
            .scheduledExecutorService(service).create();

    assertSame(service, gremlinExecutor.getScheduledExecutorService());
    gremlinExecutor.close();/*ww  w. j  a v a2s  .  c o  m*/
}

From source file:org.wso2.andes.kernel.slot.SlotManagerClusterMode.java

/**
 * Recover any messages that are persisted but not notified to the slot coordinator from killed nodes.
 * <p>/*from w ww.  j  av a2 s.  c  o m*/
 * For instance if a node get killed after persisting messages but before submitting slots,
 * until another message is published to any remaining node a new slot will not be created.
 * Hence these messages will not get delivered until another message is published.
 * <p>
 * Recover mechanism here will schedule tasks for each queue so that if no message get received within the
 * given time period that queue slot manager will create a slot and capture those messages it self.
 *
 * @param deletedNodeId node id of delete node
 */
public void deletePublisherNode(final String deletedNodeId) {

    int threadPoolCount = 1; // Single thread is suffice for this task
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("RecoverSlotsThreadPool")
            .build();
    ScheduledExecutorService recoverSlotScheduler = Executors.newScheduledThreadPool(threadPoolCount,
            namedThreadFactory);

    // this is accessed from another thread therefore using a set that supports concurrency

    Set<String> concurrentSet;

    try {
        concurrentSet = Collections
                .newSetFromMap(new ConcurrentHashMap<String, Boolean>(slotAgent.getAllQueues().size()));
        concurrentSet.addAll(slotAgent.getAllQueues());
        queuesToRecover = concurrentSet;
    } catch (AndesException ex) {
        log.error("Failed to get all queue names", ex);
    }

    recoverSlotScheduler.schedule(new Runnable() {
        @Override
        public void run() {

            try {
                long lastId = SlotMessageCounter.getInstance().getCurrentNodeSafeZoneId();
                //TODO: Delete if the queue has not progressed
                for (String queueName : queuesToRecover) {
                    // Trigger a submit slot for each queue so that new slots are created
                    // for queues that have not published any messages after a node crash
                    try {
                        updateMessageID(queueName, deletedNodeId, lastId - 1, lastId, lastId);
                    } catch (AndesException ex) {
                        log.error("Failed to update message id", ex);
                    }
                }
                slotRecoveryScheduled.set(false);
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Removing " + deletedNodeId + " from safe zone calculation.");
                    }
                    slotAgent.removePublisherNode(deletedNodeId);
                } catch (AndesException e) {
                    log.error("Failed to remove publisher node ID from safe zone calculation", e);
                }

            } catch (Throwable e) {
                log.error("Error occurred while trying to run recover slot scheduler", e);
            }
        }
    }, SlotMessageCounter.getInstance().SLOT_SUBMIT_TIMEOUT, TimeUnit.MILLISECONDS);

    slotRecoveryScheduled.set(true);

}

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

@Override
public boolean configure(final String name, final Map<String, Object> xmlParams) throws ConfigurationException {
    ReservationContextImpl.init(_entityMgr);
    VirtualMachineProfileImpl.init(_entityMgr);
    VmWorkMigrate.init(_entityMgr);/*www. j  av a2  s . c  om*/

    _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
    _nodeId = ManagementServerNode.getManagementServerId();

    _agentMgr.registerForHostEvents(this, true, true, true);

    _messageBus.subscribe(VirtualMachineManager.Topics.VM_POWER_STATE, MessageDispatcher.getDispatcher(this));

    return true;
}

From source file:org.apache.hadoop.hive.metastore.cache.CachedStore.java

@VisibleForTesting
/**//from  ww w. jav  a 2  s.  c o  m
 * This starts a background thread, which initially populates the SharedCache and later
 * periodically gets updates from the metastore db
 *
 * @param conf
 * @param runOnlyOnce
 * @param shouldRunPrewarm
 */
static synchronized void startCacheUpdateService(Configuration conf, boolean runOnlyOnce,
        boolean shouldRunPrewarm) {
    if (cacheUpdateMaster == null) {
        initBlackListWhiteList(conf);
        if (!MetastoreConf.getBoolVar(conf, ConfVars.HIVE_IN_TEST)) {
            cacheRefreshPeriodMS = MetastoreConf.getTimeVar(conf,
                    ConfVars.CACHED_RAW_STORE_CACHE_UPDATE_FREQUENCY, TimeUnit.MILLISECONDS);
        }
        LOG.info("CachedStore: starting cache update service (run every {} ms", cacheRefreshPeriodMS);
        cacheUpdateMaster = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = Executors.defaultThreadFactory().newThread(r);
                t.setName("CachedStore-CacheUpdateService: Thread-" + t.getId());
                t.setDaemon(true);
                return t;
            }
        });
        if (!runOnlyOnce) {
            cacheUpdateMaster.scheduleAtFixedRate(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0,
                    cacheRefreshPeriodMS, TimeUnit.MILLISECONDS);
        }
    }
    if (runOnlyOnce) {
        // Some tests control the execution of the background update thread
        cacheUpdateMaster.schedule(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0, TimeUnit.MILLISECONDS);
    }
}