Java Code Examples for java.util.concurrent.ScheduledThreadPoolExecutor#setContinueExistingPeriodicTasksAfterShutdownPolicy()

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#setContinueExistingPeriodicTasksAfterShutdownPolicy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigurationScheduler.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private ScheduledExecutorService getExecutorService() {
    if (executorService == null) {
        synchronized (this) {
            if (executorService == null) {
                if (scheduledItems > 0) {
                    LOGGER.debug("{} starting {} threads", name, scheduledItems);
                    scheduledItems = Math.min(scheduledItems, MAX_SCHEDULED_ITEMS);
                    final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(scheduledItems,
                            Log4jThreadFactory.createDaemonThreadFactory("Scheduled"));
                    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
                    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
                    this.executorService = executor;

                } else {
                    LOGGER.debug("{}: No scheduled items", name);
                }
            }
        }
    }
    return executorService;
}
 
Example 2
Source File: TimedSemaphore.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance of {@link TimedSemaphore} and initializes it with
 * an executor service, the given time period, and the limit. The executor
 * service will be used for creating a periodic task for monitoring the time
 * period. It can be <b>null</b>, then a default service will be created.
 *
 * @param service the executor service
 * @param timePeriod the time period
 * @param timeUnit the unit for the period
 * @param limit the limit for the semaphore
 * @throws IllegalArgumentException if the period is less or equals 0
 */
public TimedSemaphore(ScheduledExecutorService service, long timePeriod,
        TimeUnit timeUnit, int limit) {
    if (timePeriod <= 0) {
        throw new IllegalArgumentException("Time period must be greater 0!");
    }

    period = timePeriod;
    unit = timeUnit;

    if (service != null) {
        executorService = service;
        ownExecutor = false;
    } else {
        ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
                THREAD_POOL_SIZE);
        s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        executorService = s;
        ownExecutor = true;
    }

    setLimit(limit);
}
 
Example 3
Source File: ExecutorServiceHelpers.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new ScheduledExecutorService that will use daemon threads with specified priority and names.
 *
 * @param size The number of threads in the threadpool
 * @param poolName The name of the pool (this will be printed in logs)
 * @param threadPriority The priority to be assigned to the threads
 * @return A new executor service.
 */
public static ScheduledExecutorService newScheduledThreadPool(int size, String poolName, int threadPriority) {

    ThreadFactory threadFactory = getThreadFactory(poolName, threadPriority);

    // Caller runs only occurs after shutdown, as queue size is unbounded.
    ScheduledThreadPoolExecutor result = new ScheduledThreadPoolExecutor(size, threadFactory, new CallerRuns(poolName));

    // Do not execute any periodic tasks after shutdown.
    result.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);

    // Do not execute any delayed tasks after shutdown.
    result.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

    // Remove tasks from the executor once they are done executing. By default, even when canceled, these tasks are
    // not removed; if this setting is not enabled we could end up with leaked (and obsolete) tasks.
    result.setRemoveOnCancelPolicy(true);
    return result;
}
 
Example 4
Source File: TimedSemaphore.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance of {@link TimedSemaphore} and initializes it with
 * an executor service, the given time period, and the limit. The executor
 * service will be used for creating a periodic task for monitoring the time
 * period. It can be <b>null</b>, then a default service will be created.
 *
 * @param service the executor service
 * @param timePeriod the time period
 * @param timeUnit the unit for the period
 * @param limit the limit for the semaphore
 * @throws IllegalArgumentException if the period is less or equals 0
 */
public TimedSemaphore(ScheduledExecutorService service, long timePeriod,
        TimeUnit timeUnit, int limit) {
    if (timePeriod <= 0) {
        throw new IllegalArgumentException("Time period must be greater 0!");
    }

    period = timePeriod;
    unit = timeUnit;

    if (service != null) {
        executorService = service;
        ownExecutor = false;
    } else {
        ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
                THREAD_POOL_SIZE);
        s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        executorService = s;
        ownExecutor = true;
    }

    setLimit(limit);
}
 
Example 5
Source File: RateLimiter.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public RateLimiter(final ScheduledExecutorService service, final long permits, final long rateTime,
        final TimeUnit timeUnit, Supplier<Long> permitUpdater) {
    checkArgument(permits > 0, "rate must be > 0");
    checkArgument(rateTime > 0, "Renew permit time must be > 0");

    this.rateTime = rateTime;
    this.timeUnit = timeUnit;
    this.permits = permits;
    this.permitUpdater = permitUpdater;

    if (service != null) {
        this.executorService = service;
        this.externalExecutor = true;
    } else {
        final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        this.executorService = executor;
        this.externalExecutor = false;
    }

}
 
Example 6
Source File: AgentDemoUtils.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
 *
 * @param corePoolSize Number of threads to keep in the pool, even if they are idle.
 * @param threadName Part of thread name that would be used by thread factory.
 * @return Newly created scheduled thread pool.
 */
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, final String threadName) {
    ScheduledExecutorService srvc = Executors.newScheduledThreadPool(corePoolSize, new ThreadFactory() {
        @Override public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, String.format("%s-%d", threadName, THREAD_CNT.getAndIncrement()));

            thread.setDaemon(true);

            return thread;
        }
    });

    ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor)srvc;

    // Setting up shutdown policy.
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);

    return srvc;
}
 
Example 7
Source File: TimedSemaphore.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance of {@link TimedSemaphore} and initializes it with
 * an executor service, the given time period, and the limit. The executor
 * service will be used for creating a periodic task for monitoring the time
 * period. It can be <b>null</b>, then a default service will be created.
 *
 * @param service the executor service
 * @param timePeriod the time period
 * @param timeUnit the unit for the period
 * @param limit the limit for the semaphore
 * @throws IllegalArgumentException if the period is less or equals 0
 */
public TimedSemaphore(ScheduledExecutorService service, long timePeriod,
        TimeUnit timeUnit, int limit) {
    if (timePeriod <= 0) {
        throw new IllegalArgumentException("Time period must be greater 0!");
    }

    period = timePeriod;
    unit = timeUnit;

    if (service != null) {
        executorService = service;
        ownExecutor = false;
    } else {
        ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
                THREAD_POOL_SIZE);
        s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        executorService = s;
        ownExecutor = true;
    }

    setLimit(limit);
}
 
Example 8
Source File: Scheduler.java    From luxun with Apache License 2.0 5 votes vote down vote up
/**
 * create a scheduler
 * 
 * @param numThreads
 * @param baseThreadName
 * @param isDaemon
 */
public Scheduler(int numThreads, final String baseThreadName, final boolean isDaemon) {
    this.baseThreadName = baseThreadName;
    executor = new ScheduledThreadPoolExecutor(numThreads, new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, baseThreadName + threadId.getAndIncrement());
            t.setDaemon(isDaemon);
            return t;
        }
    });
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
}
 
Example 9
Source File: Animator.java    From darklaf with MIT License 5 votes vote down vote up
private static ScheduledExecutorService createScheduler() {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, r -> {
        final Thread thread = new Thread(r, "Animations Thread");
        thread.setDaemon(true);
        thread.setPriority(Thread.MAX_PRIORITY);
        return thread;
    });
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    return executor;

}
 
Example 10
Source File: Scheduler.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Create a scheduler that can be used client side. Server side, please use <code>ThreadPool.schedule</code> instead.
 *
 * Notice that if any scheduled jobs fail with an exception, these will bubble up to the uncaught exception handler where they will
 * be logged as a warning. This includes jobs started using execute, submit and schedule.
 * @param settings the settings to use
 * @return executor
 */
static ScheduledThreadPoolExecutor initScheduler(Settings settings) {
    final ScheduledThreadPoolExecutor scheduler = new SafeScheduledThreadPoolExecutor(1,
            EsExecutors.daemonThreadFactory(settings, "scheduler"), new EsAbortPolicy());
    scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    scheduler.setRemoveOnCancelPolicy(true);
    return scheduler;
}
 
Example 11
Source File: FailoverProvider.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
public FailoverProvider(List<URI> uris, Map<String, String> nestedOptions, ProviderFutureFactory futureFactory) {
    this.uris = new FailoverUriPool(uris, nestedOptions);
    this.futureFactory = futureFactory;

    // All Connection attempts happen in this executor thread as well as handling
    // failed connection events and other maintenance work.
    serializer = new ScheduledThreadPoolExecutor(1, new QpidJMSThreadFactory("FailoverProvider: async work thread", true));
    serializer.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    serializer.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}
 
Example 12
Source File: Utils.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ScheduledExecutorService} with the given properties.
 * @param numThreads The number of threads in the scheduler's thread pool.
 * @param threadNamePrefix The prefix string for thread names in this thread pool.
 * @param isDaemon {@code true} if the threads in this scheduler's should be daemon threads.
 * @return A {@link ScheduledExecutorService}.
 */
public static ScheduledExecutorService newScheduler(int numThreads, String threadNamePrefix, boolean isDaemon) {
  ScheduledThreadPoolExecutor scheduler =
      new ScheduledThreadPoolExecutor(numThreads, new SchedulerThreadFactory(threadNamePrefix, isDaemon));
  scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
  scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  return scheduler;
}
 
Example 13
Source File: RepairServiceLauncher.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * コンストラクタ. Webコンテナ起動時に呼ばれる。
 */
public RepairServiceLauncher() {
    // 同時起動はしないため、Threadは1つ.
    executor = new ScheduledThreadPoolExecutor(1);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    // リペアツールの実行をスケジュールする.
    RepairAdsService service = new RepairAdsService();
    executor.scheduleWithFixedDelay(service,
            DcCoreConfig.getAdsRepairInitialDelayInSec(),
            DcCoreConfig.getAdsRepairIntervalInSec(),
            TimeUnit.SECONDS);
    logger.info(String.format("RepairAds scheduled with delay interval %d sec.",
            DcCoreConfig.getAdsRepairIntervalInSec()));
}
 
Example 14
Source File: ThreadPooledTestSuite.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link ScheduledExecutorService} that automatically cancels ongoing tasks when shut down.
 * This is the same as ExecutorServiceHelpers.newScheduledThreadPool, however that class is not accessible from here.
 *
 * @param threadPoolSize Maximum number of threads in the pool.
 * @return A new {@link ScheduledExecutorService} instance.
 */
static ScheduledExecutorService createExecutorService(int threadPoolSize) {
    ScheduledThreadPoolExecutor es = new ScheduledThreadPoolExecutor(threadPoolSize);
    es.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    es.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    es.setRemoveOnCancelPolicy(true);
    return es;
}
 
Example 15
Source File: MatchRealtimeScheduler.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private static ListeningScheduledExecutorService newScheduler() {
    final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);
    scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    scheduler.setRemoveOnCancelPolicy(true);
    return MoreExecutors.listeningDecorator(scheduler);
}
 
Example 16
Source File: TimeService.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * <返回定时器线程池>
 */
private void getScheduledThreadPoolExecutorDaemonThread()
{
    timer = new ScheduledThreadPoolExecutor(1,new TimerThreadFactory());

    timer.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    timer.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}
 
Example 17
Source File: StatusResponseManager.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Create a StatusResponseManager with default parameters.
 */
StatusResponseManager() {
    int cap = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheSize",
                DEFAULT_CACHE_SIZE));
    cacheCapacity = cap > 0 ? cap : 0;

    int life = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheLifetime",
                DEFAULT_CACHE_LIFETIME));
    cacheLifetime = life > 0 ? life : 0;

    String uriStr = GetPropertyAction
            .privilegedGetProperty("jdk.tls.stapling.responderURI");
    URI tmpURI;
    try {
        tmpURI = ((uriStr != null && !uriStr.isEmpty()) ?
                new URI(uriStr) : null);
    } catch (URISyntaxException urise) {
        tmpURI = null;
    }
    defaultResponder = tmpURI;

    respOverride = GetBooleanAction
            .privilegedGetProperty("jdk.tls.stapling.responderOverride");
    ignoreExtensions = GetBooleanAction
            .privilegedGetProperty("jdk.tls.stapling.ignoreExtensions");

    threadMgr = new ScheduledThreadPoolExecutor(DEFAULT_CORE_THREADS,
            new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    }, new ThreadPoolExecutor.DiscardPolicy());
    threadMgr.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    threadMgr.setContinueExistingPeriodicTasksAfterShutdownPolicy(
            false);
    threadMgr.setKeepAliveTime(5000, TimeUnit.MILLISECONDS);
    threadMgr.allowCoreThreadTimeOut(true);
    responseCache = Cache.newSoftMemoryCache(
            cacheCapacity, cacheLifetime);
}
 
Example 18
Source File: LuceneDataStoreImpl.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** Open a connection to the data store. */
@Override
public void open() throws PersistenceException {
  super.open();
  /*
   * check if the storage directory is a valid serial datastore if we
   * want to support old style: String versionInVersionFile = "1.0";
   * (but this means it will open *any* directory)
   */
  try (BufferedReader isr = new BufferedReader(new FileReader(getVersionFile()))) {
    currentProtocolVersion = isr.readLine();
    String indexDirRelativePath = isr.readLine();

    if(indexDirRelativePath != null
            && indexDirRelativePath.trim().length() > 1) {
      URL storageDirURL = storageDir.toURI().toURL();
      URL theIndexURL = new URL(storageDirURL, indexDirRelativePath);
      // check if index directory exists
      File indexDir = Files.fileFromURL(theIndexURL);
      if(!indexDir.exists()) {
        throw new PersistenceException("Index directory "
                + indexDirRelativePath
                + " could not be found for datastore at " + storageDirURL);
      }

      indexURL = theIndexURL;
      this.indexer = new LuceneIndexer(indexURL);
      this.searcher = new LuceneSearcher();
      ((LuceneSearcher)this.searcher).setLuceneDatastore(this);
    }
  } catch(IOException e) {
    throw new PersistenceException("Invalid storage directory: " + e);
  }
  
  if(!isValidProtocolVersion(currentProtocolVersion))
    throw new PersistenceException("Invalid protocol version number: "
            + currentProtocolVersion);

  // Lets create a separate indexer thread which keeps running in the
  // background
  executor =
          new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory());
  // set up the executor so it does not execute delayed indexing tasks
  // that are still waiting when it is shut down. We run these tasks
  // immediately at shutdown time rather than waiting.
  executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
  executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  
  // start listening to Creole events
  Gate.getCreoleRegister().addCreoleListener(this);
}
 
Example 19
Source File: StatusResponseManager.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a StatusResponseManager with default parameters.
 */
StatusResponseManager() {
    int cap = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheSize",
                DEFAULT_CACHE_SIZE));
    cacheCapacity = cap > 0 ? cap : 0;

    int life = AccessController.doPrivileged(
            new GetIntegerAction("jdk.tls.stapling.cacheLifetime",
                DEFAULT_CACHE_LIFETIME));
    cacheLifetime = life > 0 ? life : 0;

    String uriStr = GetPropertyAction
            .privilegedGetProperty("jdk.tls.stapling.responderURI");
    URI tmpURI;
    try {
        tmpURI = ((uriStr != null && !uriStr.isEmpty()) ?
                new URI(uriStr) : null);
    } catch (URISyntaxException urise) {
        tmpURI = null;
    }
    defaultResponder = tmpURI;

    respOverride = AccessController.doPrivileged(
            new GetBooleanAction("jdk.tls.stapling.responderOverride"));
    ignoreExtensions = AccessController.doPrivileged(
            new GetBooleanAction("jdk.tls.stapling.ignoreExtensions"));

    threadMgr = new ScheduledThreadPoolExecutor(DEFAULT_CORE_THREADS,
            new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    }, new ThreadPoolExecutor.DiscardPolicy());
    threadMgr.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    threadMgr.setContinueExistingPeriodicTasksAfterShutdownPolicy(
            false);
    threadMgr.setKeepAliveTime(5000, TimeUnit.MILLISECONDS);
    threadMgr.allowCoreThreadTimeOut(true);
    responseCache = Cache.newSoftMemoryCache(
            cacheCapacity, cacheLifetime);
}