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

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#setKeepAliveTime() . 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: ThreadRestarts.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(boolean allowTimeout) throws Exception {
    CountingThreadFactory ctf = new CountingThreadFactory();
    ScheduledThreadPoolExecutor stpe
        = new ScheduledThreadPoolExecutor(10, ctf);
    try {
        // schedule a dummy task in the "far future"
        Runnable nop = new Runnable() { public void run() {}};
        stpe.schedule(nop, FAR_FUTURE_MS, MILLISECONDS);
        stpe.setKeepAliveTime(1L, MILLISECONDS);
        stpe.allowCoreThreadTimeOut(allowTimeout);
        MILLISECONDS.sleep(12L);
    } finally {
        stpe.shutdownNow();
        if (!stpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS))
            throw new AssertionError("timed out");
    }
    if (ctf.count.get() > 1)
        throw new AssertionError(
            String.format("%d threads created, 1 expected",
                          ctf.count.get()));
}
 
Example 2
Source File: TraceGrpcApiService.java    From cloud-trace-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new TraceGrpcApiService.
 */
public TraceGrpcApiService build() throws IOException {
  if (credentials == null) {
    credentials = GoogleCredentials.getApplicationDefault();
  }

  if(executorService == null) {
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
    // Have the flushing threads shutdown if idle for the scheduled delay.
    scheduledThreadPoolExecutor.setKeepAliveTime(scheduledDelay, TimeUnit.SECONDS);
    scheduledThreadPoolExecutor.allowCoreThreadTimeOut(true);
    executorService = scheduledThreadPoolExecutor;
  }

  return new TraceGrpcApiService(projectId, optionsFactory, bufferSize,
      scheduledDelay, credentials, executorService);
}
 
Example 3
Source File: Utilities.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("SameParameterValue")
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name,
                                                                         int corePoolSize,
                                                                         int maximumPoolSize,
                                                                         long keepAliveTimeInSec) {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat(name)
            .setDaemon(true)
            .setPriority(Thread.MIN_PRIORITY)
            .build();
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    executor.setKeepAliveTime(keepAliveTimeInSec, TimeUnit.SECONDS);
    executor.allowCoreThreadTimeOut(true);
    executor.setMaximumPoolSize(maximumPoolSize);
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    executor.setRejectedExecutionHandler((r, e) -> log.debug("RejectedExecutionHandler called"));
    return executor;
}
 
Example 4
Source File: LibJoynrMessageRouterTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
ScheduledExecutorService provideMessageSchedulerThreadPoolExecutor() {
    ThreadFactory schedulerNamedThreadFactory = new JoynrThreadFactory("joynr.MessageScheduler-scheduler");
    ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(2, schedulerNamedThreadFactory);
    scheduler.setKeepAliveTime(100, TimeUnit.SECONDS);
    scheduler.allowCoreThreadTimeOut(true);
    return scheduler;
}
 
Example 5
Source File: DefaultScheduledExecutorServiceProvider.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Inject
public DefaultScheduledExecutorServiceProvider(@Named(ConfigurableMessagingSettings.PROPERTY_MESSAGING_MAXIMUM_PARALLEL_SENDS) int maximumParallelSends,
                                               ShutdownNotifier shutdownNotifier) {
    ThreadFactory schedulerNamedThreadFactory = new JoynrThreadFactory("ScheduledExecutorService", true);

    /*
     * Number of required threads (numbers in parentheses mean: no dedicated thread is required here):
     *
     * MessageRouter: #maximumParallelSends (default: 20) messageWorkers
     *                (1) routingTableCleanup
     * ArbitratorFactory: 1 arbitratorRunnable
     * MessagingSkeletonFactory: 1 per skeleton (transport), only required during startup, can be executed one after the other
     * HttpBridgeEndpointRegistryClient: N/A (JEE only): uses scheduledExecutorServcie of the application server
     * MqttPahoClientFactory: 4 per Mqtt connection?
     * ExpiredDiscoveryEntryCacheCleaner: (1) cleanupAction
     * RequestReplyManagerImpl: (1) cleanupScheduler for queued requests
     * PublicationManagerImpl: (1) cleanupScheduler for subscriptions
     * SubscriptionManagerImpl: (1) cleanupScheduler for subscriptions
     * ReplyCallerDirectory: (1) cleanupScheduler for ReplyCallers
    */
    scheduler = new ScheduledThreadPoolExecutor(maximumParallelSends + MAX_SKELETON_THREADS + MQTT_THREADS,
                                                schedulerNamedThreadFactory);
    scheduler.setKeepAliveTime(100, TimeUnit.SECONDS);
    scheduler.allowCoreThreadTimeOut(true);

    shutdownNotifier.registerToBeShutdownAsLast(this);
}
 
Example 6
Source File: LifecycleSupervisor.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
public LifecycleSupervisor() {
  lifecycleState = LifecycleState.IDLE;
  supervisedProcesses = new HashMap<LifecycleAware, Supervisoree>();
  monitorFutures = new HashMap<LifecycleAware, ScheduledFuture<?>>();
  monitorService = new ScheduledThreadPoolExecutor(10,
      new ThreadFactoryBuilder().setNameFormat(
          "lifecycleSupervisor-" + Thread.currentThread().getId() + "-%d")
          .build());
  monitorService.setMaximumPoolSize(20);
  monitorService.setKeepAliveTime(30, TimeUnit.SECONDS);
  purger = new Purger();
  needToPurge = false;
}
 
Example 7
Source File: ScheduledThreadPoolService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void start(final StartContext context) throws StartException {
    ScheduledThreadPoolExecutor scheduledExecutor = new ExecutorImpl(0, threadFactoryValue.getValue());
    scheduledExecutor.setCorePoolSize(maxThreads);
    if (keepAlive != null) scheduledExecutor.setKeepAliveTime(keepAlive.getDuration(), keepAlive.getUnit());
    final ManagedScheduledExecutorService executorService = new ManagedScheduledExecutorService(scheduledExecutor);
    synchronized (this) {
        executor = executorService;
    }
}
 
Example 8
Source File: ServiceQueue.java    From asteria-3.0 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates and configures a new {@link ScheduledExecutorService} with a
 * timeout value of {@code seconds}. If the timeout value is below or equal
 * to zero then the returned executor will never timeout.
 *
 * @return the newly created and configured executor service.
 */
private static ScheduledExecutorService createServiceExecutor(long seconds) {
    Preconditions.checkArgument(seconds >= 0, "The timeout value must be equal to or greater than 0!");
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    executor.setRejectedExecutionHandler(new CallerRunsPolicy());
    executor.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("ServiceQueueThread").build());
    if (seconds > 0) {
        executor.setKeepAliveTime(seconds, TimeUnit.SECONDS);
        executor.allowCoreThreadTimeOut(true);
    }
    return executor;
}
 
Example 9
Source File: TaskMonitor.java    From helios with Apache License 2.0 5 votes vote down vote up
public TaskMonitor(final JobId jobId, final FlapController flapController,
                   final StatusUpdater statusUpdater) {
  this.jobId = jobId;
  this.flapController = flapController;
  this.statusUpdater = statusUpdater;

  final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
  // Let core threads time out to avoid unnecessarily keeping a flapping state check thread alive
  // for the majority of tasks that do not flap.
  executor.setKeepAliveTime(5, SECONDS);
  executor.allowCoreThreadTimeOut(true);
  this.scheduler = MoreExecutors.getExitingScheduledExecutorService(executor, 0, SECONDS);
}
 
Example 10
Source File: DeletionService.java    From incubator-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 11
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 12
Source File: ArmeriaServerFactory.java    From armeria with Apache License 2.0 5 votes vote down vote up
private ScheduledThreadPoolExecutor newBlockingTaskExecutor() {
    final ScheduledThreadPoolExecutor blockingTaskExecutor = new ScheduledThreadPoolExecutor(
            getMaxThreads(),
            ThreadFactories.newThreadFactory("armeria-dropwizard-blocking-tasks", true));
    blockingTaskExecutor.setKeepAliveTime(60, TimeUnit.SECONDS);
    blockingTaskExecutor.allowCoreThreadTimeOut(true);
    return blockingTaskExecutor;
}
 
Example 13
Source File: ReconnectManager.java    From sailfish with Apache License 2.0 5 votes vote down vote up
private ReconnectManager(){
    reconnectExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread();
            t.setName("sailfish-ReconnectManager");
            t.setDaemon(true);
            return t;
        }
    });
    reconnectExecutor.setKeepAliveTime(1, TimeUnit.MINUTES);
}
 
Example 14
Source File: ExecutionPool.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static ScheduledExecutorService getScheduledExecutor(ThreadGroup group, String namePrefix, int threadCount, long keepAliveSeconds, boolean preStart) {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(threadCount, new ExecutionPoolThreadFactory(group, namePrefix));
    if (keepAliveSeconds > 0) {
        executor.setKeepAliveTime(keepAliveSeconds, TimeUnit.SECONDS);
        executor.allowCoreThreadTimeOut(true);
    }
    if (preStart) {
        executor.prestartAllCoreThreads();
    }
    return executor;
}
 
Example 15
Source File: TimeoutThreadPoolBuilder.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link ScheduledThreadPoolExecutor} with custom name for the threads.
 *
 * @param name the prefix to add to the thread name in ThreadFactory.
 * @return The default thread pool for request timeout and client execution timeout features.
 */
public static ScheduledThreadPoolExecutor buildDefaultTimeoutThreadPool(final String name) {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5, getThreadFactory(name));
    safeSetRemoveOnCancel(executor);
    executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    executor.allowCoreThreadTimeOut(true);

    return executor;
}
 
Example 16
Source File: DefaultRunLoop.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public DefaultRunLoop() {
  int threadsInPool = 1;
  ThreadFactory threadFactory = new FirebaseThreadFactory();
  executor =
      new ScheduledThreadPoolExecutor(threadsInPool, threadFactory) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
          super.afterExecute(r, t);
          if (t == null && r instanceof Future<?>) {
            Future<?> future = (Future<?>) r;
            try {
              // Not all Futures will be done, e.g. when used with scheduledAtFixedRate
              if (future.isDone()) {
                future.get();
              }
            } catch (CancellationException ce) {
              // Cancellation exceptions are okay, we expect them to happen sometimes
            } catch (ExecutionException ee) {
              t = ee.getCause();
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          }
          if (t != null) {
            handleException(t);
          }
        }
      };

  // Core threads don't time out, this only takes effect when we drop the number of required
  // core threads
  executor.setKeepAliveTime(3, TimeUnit.SECONDS);
}
 
Example 17
Source File: AsyncQueue.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
SynchronizedShutdownAwareExecutor() {
  DelayedStartFactory threadFactory = new DelayedStartFactory();

  thread = Executors.defaultThreadFactory().newThread(threadFactory);
  thread.setName("FirestoreWorker");
  thread.setDaemon(true);
  thread.setUncaughtExceptionHandler((crashingThread, throwable) -> panic(throwable));

  internalExecutor =
      new ScheduledThreadPoolExecutor(1, threadFactory) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
          super.afterExecute(r, t);
          if (t == null && r instanceof Future<?>) {
            Future<?> future = (Future<?>) r;
            try {
              // Not all Futures will be done, e.g. when used with scheduledAtFixedRate
              if (future.isDone()) {
                future.get();
              }
            } catch (CancellationException ce) {
              // Cancellation exceptions are okay, we expect them to happen sometimes
            } catch (ExecutionException ee) {
              t = ee.getCause();
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          }
          if (t != null) {
            panic(t);
          }
        }
      };

  // Core threads don't time out, this only takes effect when we drop the number of required
  // core threads
  internalExecutor.setKeepAliveTime(3, TimeUnit.SECONDS);

  isShuttingDown = false;
}
 
Example 18
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 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);
}