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

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#allowCoreThreadTimeOut() . 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: 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 5
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 6
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 7
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 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: 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 10
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 11
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);
}
 
Example 12
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);
}