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

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#setExecuteExistingDelayedTasksAfterShutdownPolicy() . 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: 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 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: ConsistencyWatchdogServer.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void start() {
  if (!session.isHost())
    throw new IllegalStateException("Component can only be run on the session's host");

  session.addActivityProducer(this);
  stopManager.addBlockable(this);
  editorManager.addSharedEditorListener(sharedEditorListener);

  checksumCalculationExecutor =
      new ScheduledThreadPoolExecutor(
          1, new NamedThreadFactory("Consistency-Watchdog-Server", false));

  checksumCalculationExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

  checksumCalculationFuture =
      checksumCalculationExecutor.scheduleWithFixedDelay(
          checksumCalculation, 0, CHECKSUM_CALCULATION_INTERVAL, TimeUnit.MILLISECONDS);
}
 
Example 4
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 5
Source File: SolrRrdBackendFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Create a factory.
 * @param solrClient SolrClient to use
 * @param collection collection name where documents are stored (typically this is
 *                   {@link CollectionAdminParams#SYSTEM_COLL})
 * @param syncPeriod synchronization period in seconds - how often modified
 *                   databases are stored as updated Solr documents
 * @param timeSource time source
 */
public SolrRrdBackendFactory(SolrClient solrClient, String collection, int syncPeriod, TimeSource timeSource) {
  this.solrClient = solrClient;
  this.timeSource = timeSource;
  this.collection = collection;
  this.syncPeriod = syncPeriod;
  if (log.isDebugEnabled()) {
    log.debug("Created {}", hashCode());
  }
  this.idPrefixLength = ID_PREFIX.length() + ID_SEP.length();
  syncService = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2,
      new SolrNamedThreadFactory("SolrRrdBackendFactory"));
  syncService.setRemoveOnCancelPolicy(true);
  syncService.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  syncService.scheduleWithFixedDelay(() -> maybeSyncBackends(),
      timeSource.convertDelay(TimeUnit.SECONDS, syncPeriod, TimeUnit.MILLISECONDS),
      timeSource.convertDelay(TimeUnit.SECONDS, syncPeriod, TimeUnit.MILLISECONDS),
      TimeUnit.MILLISECONDS);
}
 
Example 6
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 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: DeletionService.java    From tajo with Apache License 2.0 5 votes vote down vote up
public DeletionService(int defaultThreads, int debugDelay) {
  ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("DeletionService #%d").build();

  sched = new ScheduledThreadPoolExecutor(defaultThreads, tf);
  sched.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  sched.setKeepAliveTime(60L, TimeUnit.SECONDS);
  this.debugDelay = debugDelay;
}
 
Example 9
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 10
Source File: Modbus.java    From modbus with Apache License 2.0 5 votes vote down vote up
/**
 * @return a shared {@link ScheduledExecutorService}.
 */
public static synchronized ScheduledExecutorService sharedScheduledExecutor() {
    if (SCHEDULED_EXECUTOR_SERVICE == null) {
        ThreadFactory threadFactory = new ThreadFactory() {
            private final AtomicLong threadNumber = new AtomicLong(0L);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, "modbus-shared-scheduled-executor-" + threadNumber.getAndIncrement());
                thread.setDaemon(true);
                thread.setUncaughtExceptionHandler(
                    (t, e) ->
                        LoggerFactory.getLogger(Modbus.class)
                            .warn("Uncaught Exception on shared stack ScheduledExecutorService thread!", e)
                );
                return thread;
            }
        };

        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            threadFactory
        );

        executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

        SCHEDULED_EXECUTOR_SERVICE = executor;
    }

    return SCHEDULED_EXECUTOR_SERVICE;
}
 
Example 11
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 12
Source File: ScheduledTriggers.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public ScheduledTriggers(SolrResourceLoader loader, SolrCloudManager cloudManager) {
  scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(DEFAULT_TRIGGER_CORE_POOL_SIZE,
      new SolrNamedThreadFactory("ScheduledTrigger"));
  scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);
  scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  actionExecutor = ExecutorUtil.newMDCAwareSingleThreadExecutor(new SolrNamedThreadFactory("AutoscalingActionExecutor"));
  this.cloudManager = cloudManager;
  this.stateManager = cloudManager.getDistribStateManager();
  this.loader = loader;
  queueStats = new Stats();
  listeners = new TriggerListeners();
  // initialize cooldown timer
  cooldownStart.set(cloudManager.getTimeSource().getTimeNs() - cooldownPeriod.get());
}
 
Example 13
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 14
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 15
Source File: ExecService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static void start() {
   synchronized (START_LOCK) {
      if (scheduled != null || blocking != null) {
         throw new IllegalStateException("exec service already started");
      }

      // TODO: the thread pool size here may need to be tuned
      ScheduledThreadPoolExecutor sch = new ScheduledThreadPoolExecutor(SC_POOL_SIZE, new Factory("irsh"));
      sch.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
      sch.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);

      // TODO: the thread pool size here may need to be tuned
      BlockingQueue<Runnable> queue = new LimitedSizeBlockingQueue<>(IO_QUEUE_SIZE, DEFAULT_IO_MAX_BLOCK_TIME, TimeUnit.NANOSECONDS);
      ThreadPoolExecutor blk = new ThreadPoolExecutor(IO_POOL_SIZE, IO_POOL_SIZE, 60, TimeUnit.SECONDS, queue, new Factory("irio"));
      blk.allowCoreThreadTimeOut(false);

      // TODO: the thread pool size here may need to be tuned
      //queue = new LinkedBlockingQueue<>();
      queue = new LimitedSizeBlockingQueue<>(BK_QUEUE_SIZE, DEFAULT_BK_MAX_BLOCK_TIME, TimeUnit.NANOSECONDS);
      ThreadPoolExecutor bgrnd = new ThreadPoolExecutor(BK_POOL_SIZE, BK_POOL_SIZE, 60, TimeUnit.SECONDS, queue, new Factory("irbk"));
      blk.allowCoreThreadTimeOut(false);

      WatchdogChecks.addExecutorWatchdog("system scheduled executor", sch);
      WatchdogChecks.addExecutorWatchdog("system io executor", blk);
      WatchdogChecks.addExecutorWatchdog("system background io executor", bgrnd);

      scheduled = sch;
      blocking = blk;
      background = bgrnd;
   }
}
 
Example 16
Source File: HostControllerService.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public synchronized void start(final StartContext context) throws StartException {
    scheduledExecutorService = new ScheduledThreadPoolExecutor(4 , threadFactory);
    scheduledExecutorService.setExecuteExistingDelayedTasksAfterShutdownPolicy(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: ServerService.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public synchronized void start(final StartContext context) throws StartException {
    scheduledExecutorService = new ScheduledThreadPoolExecutor(4 , threadFactory);
    scheduledExecutorService.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
}
 
Example 20
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);
}