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

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy() . 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: 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 2
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 3
Source File: CommonResources.java    From open-ig with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
	 * Constructor. Initializes and loads all resources.
	 * @param config the configuration object.
	 * @param control the general control
	 */
	public CommonResources(Configuration config, GameControls control) {
		this.config = config;
		this.control = control;
		this.profile = new Profile();
		this.profile.name = config.currentProfile;
		
		int ncpu = Runtime.getRuntime().availableProcessors();
		ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(ncpu, new BasicThreadFactory());
//		scheduler.setKeepAliveTime(1500, TimeUnit.MILLISECONDS);
//		scheduler.allowCoreThreadTimeOut(true);
		scheduler.setRemoveOnCancelPolicy(true);
		pool = scheduler;

		init();
	}
 
Example 4
Source File: AsyncReporter.java    From buffer-slayer with Apache License 2.0 6 votes vote down vote up
@Override
protected ScheduledExecutorService scheduler() {
  if (this.scheduler == null) {
    synchronized (this) {
      if (this.scheduler == null) {
        ThreadFactory timerFactory = new ThreadFactoryBuilder()
            .setNameFormat("AsyncReporter-" + id + "-timer-%d")
            .setDaemon(true)
            .build();
        ScheduledThreadPoolExecutor timerPool =
            new ScheduledThreadPoolExecutor(timerThreads, timerFactory);
        timerPool.setRemoveOnCancelPolicy(true);
        this.scheduler = timerPool;
        return timerPool;
      }
    }
  }
  return scheduler;
}
 
Example 5
Source File: StatsdClient.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Constructs a new StatsD client.
 *
 * @param prefix   StatsD prefix
 * @param hostname StatsD collector hostname (default localhost)
 * @param port     StatsD collector listener port (default 8125)
 */
public StatsdClient(String prefix, String hostname, int port) throws StatsDClientException {
    this.hostname = hostname;
    this.prefix = prefix;
    this.port = port;

    this.lock = new ReentrantReadWriteLock();
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    exec.setRemoveOnCancelPolicy(true);

    Runnable refreshClient = new Runnable() {
        @Override
        public void run() {
            newClient();
        }
    };
    exec.scheduleAtFixedRate(refreshClient, CLIENT_TTL, CLIENT_TTL, TimeUnit.SECONDS);

    this.newClient();
    LOGGER.info("StatsdClient wrapper created. " + this.hashCode());
}
 
Example 6
Source File: EventSchedulerService.java    From flux with Apache License 2.0 6 votes vote down vote up
@Inject
public EventSchedulerService(EventSchedulerDao eventSchedulerDao, EventSchedulerRegistry eventSchedulerRegistry,
                             @Named("eventScheduler.batchRead.intervalms") Integer batchReadInterval,
                             @Named("eventScheduler.batchRead.batchSize") Integer batchSize,
                             ObjectMapper objectMapper) {
    this.eventSchedulerDao = eventSchedulerDao;
    this.eventSchedulerRegistry = eventSchedulerRegistry;
    this.batchReadInterval = batchReadInterval;
    this.batchSize = batchSize;
    this.objectMapper = objectMapper;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // remove the task from scheduler on cancel
    executor.setRemoveOnCancelPolicy(true);
    scheduledExecutorService =
            new InstrumentedScheduledExecutorService(Executors.unconfigurableScheduledExecutorService(executor),
                    SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledExectorSvcName);
}
 
Example 7
Source File: ThreadManager.java    From sepia-assist-server with MIT License 6 votes vote down vote up
/**
 * Schedule a task to run in background after certain delay and then forget about it. Keep in mind that this means you cannot stop it once scheduled.<br>
 * <br>
 * CAREFUL: The user is responsible for the task ESPECIALLY that it will not get stuck in a loop and does not run FOREVER!<br>
 * <br>
 * For a more advanced version of this check {@link ServiceBackgroundTaskManager#runOnceInBackground}.
 * @param delayMs - execute after this time in milliseconds
 * @param task - Runnable to run
 * @return true if the task was scheduled (NOT executed)
 */
public static boolean scheduleBackgroundTaskAndForget(long delayMs, Runnable task){
	String taskId = getNewFutureId();
	int corePoolSize = 1;
    final ScheduledThreadPoolExecutor executor = getNewScheduledThreadPool(corePoolSize);
    executor.setRemoveOnCancelPolicy(true);
    ScheduledFuture<?> future =	executor.schedule(() -> {
    	//run task and...
    	try{
    		increaseThreadCounter();
    		task.run();
    		decreaseThreadCounter();
    	}catch (Exception e){
    		decreaseThreadCounter();
		}
    	//... remove yourself from manager
    	removeFromFutureMap(taskId);
    	executor.purge();
    	executor.shutdown();
    	return;
    }, delayMs, TimeUnit.MILLISECONDS);
    //track
    addToFutureMap(taskId, future);
    return true;
}
 
Example 8
Source File: ResponseCacher.java    From xipki with Apache License 2.0 5 votes vote down vote up
public void init() {
  updateCacheStore();

  scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
  scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);

  // check every 600 seconds (10 minutes)
  this.responseCleaner = scheduledThreadPoolExecutor.scheduleAtFixedRate(
      new ExpiredResponsesCleaner(), 348, 600, TimeUnit.SECONDS);

  // check every 600 seconds (10 minutes)
  this.issuerUpdater = scheduledThreadPoolExecutor.scheduleAtFixedRate(
      new IssuerUpdater(), 448, 600, TimeUnit.SECONDS);
}
 
Example 9
Source File: ExecutorScheduler.java    From lite-pool with Apache License 2.0 5 votes vote down vote up
protected void doStart() throws Exception {
	// 1
	super.doStart();
	
	// 2
	this.factory.compareAndSet(null, new XThreadFactory(name, false));
	ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(this.corePoolSize);
	s.setRemoveOnCancelPolicy(true); s.setThreadFactory(factory.get()); executor.set(s);
}
 
Example 10
Source File: StatusScheduler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to initialize this class to use internal executor.
 * <p/>
 * This method must be called before first usage of {@link #getInstance()}
 * method. Caller should hold <code>StatusScheduler.class</code> lock.
 */
private static ScheduledThreadPoolExecutor newScheduledExecutor() {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
            DEFAULT_INTERNAL_CORE_POOL_SIZE, new ThreadFactory());
    executor.setRemoveOnCancelPolicy(true);
    return executor;
}
 
Example 11
Source File: AmazonSQSVirtualQueuesClient.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 5 votes vote down vote up
private static ScheduledExecutorService createIdleQueueDeletionExecutor() {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1,
            new DaemonThreadFactory("AmazonSQSVirtualQueuesClient"));
    // Since we are cancelling and resubmitting a task on every heartbeat,
    // without this setting the size of the work queue will depend on the number of
    // heartbeat calls made within the retention period, and hence on the TPS made to
    // the queue. That can lead to increased memory pressure, possibly even exhausting
    // memory.
    executor.setRemoveOnCancelPolicy(true);
    return executor;
}
 
Example 12
Source File: DelayedConfigResponses.java    From vespa with Apache License 2.0 5 votes vote down vote up
DelayedConfigResponses(RpcServer rpcServer, int numTimerThreads, boolean useJrtWatcher) {
    this.rpcServer = rpcServer;
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(numTimerThreads, ThreadFactoryFactory.getThreadFactory(DelayedConfigResponses.class.getName()));
    executor.setRemoveOnCancelPolicy(true);
    this.executorService = executor;
    this.useJrtWatcher = useJrtWatcher;
}
 
Example 13
Source File: TimedAssessmentQueue.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private TimedAssessmentQueue() { 
  queue = new ConcurrentHashMap();
  tasks = new HashMap();
  // Get any custom thread count, or default to 4
  int threads = ServerConfigurationService.getInt("samigo.timerThreadCount", 4);
  log.info( "SAMIGO_TIMED_ASSESSMENT:QUEUE:INIT: THREADS:" + threads + " (Set property 'samigo.timerThreadCount' to adjust.)");
  threadPool = new ScheduledThreadPoolExecutor(threads);
  // Set the default removal policy so we don't leak memory with finished tasks
  threadPool.setRemoveOnCancelPolicy(true);
}
 
Example 14
Source File: PluginOutputAsyncerImpl.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Inject
public PluginOutputAsyncerImpl(@NotNull final ShutdownHooks shutdownHooks) {
    this.shutdownHooks = shutdownHooks;

    final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    //enable removing canceled tasks from the executor queue
    executor.setRemoveOnCancelPolicy(true);
    executor.setThreadFactory(ThreadFactoryUtil.create("extension-timeout-executor-%d"));
    //for instrumentation (metrics)
    scheduledExecutor = executor;
}
 
Example 15
Source File: SingleScheduler.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates the default {@link ScheduledExecutorService} for the SingleScheduler
 * ({@code Executors.newScheduledThreadPoolExecutor} with core and max pool size of 1).
 */
@Override
public ScheduledExecutorService get() {
	ScheduledThreadPoolExecutor e = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, this.factory);
	e.setRemoveOnCancelPolicy(true);
	e.setMaximumPoolSize(1);
	return e;
}
 
Example 16
Source File: CWLInstanceScheduler.java    From cwlexec with Apache License 2.0 4 votes vote down vote up
private CWLInstanceScheduler() {
    ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(10);
    scheduledExecutor.setRemoveOnCancelPolicy(true);
    this.service = scheduledExecutor;
}
 
Example 17
Source File: TimeoutScheduler.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
private static ScheduledThreadPoolExecutor newExecutor() {
  LOG.debug("new ScheduledThreadPoolExecutor");
  final ScheduledThreadPoolExecutor e = new ScheduledThreadPoolExecutor(1, (ThreadFactory) Daemon::new);
  e.setRemoveOnCancelPolicy(true);
  return e;
}
 
Example 18
Source File: SingleTimedScheduler.java    From reactive-streams-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a new SingleTimedScheduler with the given thread factory.
 * @param threadFactory the thread factory to use
 */
public SingleTimedScheduler(ThreadFactory threadFactory) {
    ScheduledThreadPoolExecutor e = (ScheduledThreadPoolExecutor)Executors.newScheduledThreadPool(1, threadFactory);
    e.setRemoveOnCancelPolicy(true);
    executor = e;
}
 
Example 19
Source File: ProgressTaskLogger.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private static ScheduledExecutorService createExecutorService() {
  ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1,
      new ThreadFactoryBuilder().setNameFormat("task-logging-%d").build());
  executor.setRemoveOnCancelPolicy(true);
  return executor;
}