java.util.concurrent.ThreadPoolExecutor.setKeepAliveTime()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(10.9k)|赞(0)|评价(0)|浏览(99)

本文整理了Java中java.util.concurrent.ThreadPoolExecutor.setKeepAliveTime()方法的一些代码示例,展示了ThreadPoolExecutor.setKeepAliveTime()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ThreadPoolExecutor.setKeepAliveTime()方法的具体详情如下:
包路径:java.util.concurrent.ThreadPoolExecutor
类名称:ThreadPoolExecutor
方法名:setKeepAliveTime

ThreadPoolExecutor.setKeepAliveTime介绍

[英]Sets the time limit for which threads may remain idle before being terminated. If there are more than the core number of threads currently in the pool, after waiting this amount of time without processing a task, excess threads will be terminated. This overrides any value set in the constructor.
[中]设置线程在终止前可以保持空闲的时间限制。如果池中的线程数超过当前的核心线程数,在等待这段时间而不处理任务后,多余的线程将被终止。这将覆盖构造函数中设置的任何值。

代码示例

代码示例来源:origin: spring-projects/spring-framework

/**
 * Set the ThreadPoolExecutor's keep-alive seconds.
 * Default is 60.
 * <p><b>This setting can be modified at runtime, for example through JMX.</b>
 */
public void setKeepAliveSeconds(int keepAliveSeconds) {
  synchronized (this.poolSizeMonitor) {
    this.keepAliveSeconds = keepAliveSeconds;
    if (this.threadPoolExecutor != null) {
      this.threadPoolExecutor.setKeepAliveTime(keepAliveSeconds, TimeUnit.SECONDS);
    }
  }
}

代码示例来源:origin: org.springframework/spring-context

/**
 * Set the ThreadPoolExecutor's keep-alive seconds.
 * Default is 60.
 * <p><b>This setting can be modified at runtime, for example through JMX.</b>
 */
public void setKeepAliveSeconds(int keepAliveSeconds) {
  synchronized (this.poolSizeMonitor) {
    this.keepAliveSeconds = keepAliveSeconds;
    if (this.threadPoolExecutor != null) {
      this.threadPoolExecutor.setKeepAliveTime(keepAliveSeconds, TimeUnit.SECONDS);
    }
  }
}

代码示例来源:origin: wildfly/wildfly

public TP setThreadPoolKeepAliveTime(long time) {
  thread_pool_keep_alive_time=time;
  if(thread_pool instanceof ThreadPoolExecutor)
    ((ThreadPoolExecutor)thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS);
  return this;
}

代码示例来源:origin: wildfly/wildfly

public void    setKeepAliveTime(long time)           {condSet(p -> p.setKeepAliveTime(time, TimeUnit.MILLISECONDS));}
public int     getCurrentThreads()                   {return condGet(ThreadPoolExecutor::getPoolSize, 0);}

代码示例来源:origin: Atmosphere/atmosphere

private static void keepAliveThreads(AbstractExecutorService t, AtmosphereConfig config) {
  if (!ThreadPoolExecutor.class.isAssignableFrom(t.getClass())) {
    return;
  }
  ThreadPoolExecutor e = ThreadPoolExecutor.class.cast(t);
  int keepAlive = DEFAULT_KEEP_ALIVE;
  String s = config.getInitParameter(ApplicationConfig.EXECUTORFACTORY_KEEP_ALIVE);
  if (s != null) {
    keepAlive = Integer.parseInt(s);
  }
  e.setKeepAliveTime(keepAlive, TimeUnit.SECONDS);
  e.allowCoreThreadTimeOut(config.getInitParameter(ApplicationConfig.ALLOW_CORE_THREAD_TIMEOUT, true));
}

代码示例来源:origin: com.zaxxer/HikariCP

private void createNetworkTimeoutExecutor(final DataSource dataSource, final String dsClassName, final String jdbcUrl)
{
 // Temporary hack for MySQL issue: http://bugs.mysql.com/bug.php?id=75615
 if ((dsClassName != null && dsClassName.contains("Mysql")) ||
   (jdbcUrl != null && jdbcUrl.contains("mysql")) ||
   (dataSource != null && dataSource.getClass().getName().contains("Mysql"))) {
   netTimeoutExecutor = new SynchronousExecutor();
 }
 else {
   ThreadFactory threadFactory = config.getThreadFactory();
   threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory(poolName + " network timeout executor", true);
   ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(threadFactory);
   executor.setKeepAliveTime(15, SECONDS);
   executor.allowCoreThreadTimeOut(true);
   netTimeoutExecutor = executor;
 }
}

代码示例来源:origin: apache/hbase

private ThreadPoolExecutor disableHandlers(RpcScheduler scheduler) {
 ThreadPoolExecutor rpcExecutor=null;
 try {
  Field ExecutorField = scheduler.getClass().getDeclaredField("executor");
  ExecutorField.setAccessible(true);
  scheduler.start();
  rpcExecutor = (ThreadPoolExecutor) ExecutorField.get(scheduler);
  rpcExecutor.setMaximumPoolSize(1);
  rpcExecutor.allowCoreThreadTimeOut(true);
  rpcExecutor.setCorePoolSize(0);
  rpcExecutor.setKeepAliveTime(1, TimeUnit.MICROSECONDS);
  // Wait for 2 seconds, so that idle threads will die
  Thread.sleep(2000);
 } catch (NoSuchFieldException e) {
  LOG.error("No such field exception:"+e);
 } catch (IllegalAccessException e) {
  LOG.error("Illegal access exception:"+e);
 } catch (InterruptedException e) {
  LOG.error("Interrupted exception:"+e);
 }
 return rpcExecutor;
}

代码示例来源:origin: PipelineAI/pipeline

private void touchConfig() {
  final int dynamicCoreSize = properties.coreSize().get();
  final int configuredMaximumSize = properties.maximumSize().get();
  int dynamicMaximumSize = properties.actualMaximumSize();
  final boolean allowSizesToDiverge = properties.getAllowMaximumSizeToDivergeFromCoreSize().get();
  boolean maxTooLow = false;
  if (allowSizesToDiverge && configuredMaximumSize < dynamicCoreSize) {
    //if user sets maximum < core (or defaults get us there), we need to maintain invariant of core <= maximum
    dynamicMaximumSize = dynamicCoreSize;
    maxTooLow = true;
  }
  // In JDK 6, setCorePoolSize and setMaximumPoolSize will execute a lock operation. Avoid them if the pool size is not changed.
  if (threadPool.getCorePoolSize() != dynamicCoreSize || (allowSizesToDiverge && threadPool.getMaximumPoolSize() != dynamicMaximumSize)) {
    if (maxTooLow) {
      logger.error("Hystrix ThreadPool configuration for : " + metrics.getThreadPoolKey().name() + " is trying to set coreSize = " +
          dynamicCoreSize + " and maximumSize = " + configuredMaximumSize + ".  Maximum size will be set to " +
          dynamicMaximumSize + ", the coreSize value, since it must be equal to or greater than the coreSize value");
    }
    threadPool.setCorePoolSize(dynamicCoreSize);
    threadPool.setMaximumPoolSize(dynamicMaximumSize);
  }
  threadPool.setKeepAliveTime(properties.keepAliveTimeMinutes().get(), TimeUnit.MINUTES);
}

代码示例来源:origin: geoserver/geoserver

executor.setCorePoolSize(coverageAccess.getCorePoolSize());
executor.setMaximumPoolSize(coverageAccess.getMaxPoolSize());
executor.setKeepAliveTime(
    coverageAccess.getKeepAliveTime(), TimeUnit.MILLISECONDS);
coverageAccess.setThreadPoolExecutor(executor);

代码示例来源:origin: org.eclipse.jetty/jetty-util

/**
 * <p>Sets the maximum thread idle time in ms.</p>
 * <p>Threads that are idle for longer than this
 * period may be stopped.</p>
 *
 * @param idleTimeout the maximum thread idle time in ms.
 * @see #getIdleTimeout()
 */
public void setIdleTimeout(int idleTimeout)
{
  _executor.setKeepAliveTime(idleTimeout, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: camunda/camunda-bpm-platform

public void setKeepAliveTime(long time, TimeUnit unit) {
 threadPoolExecutor.setKeepAliveTime(time, unit);
}

代码示例来源:origin: camunda/camunda-bpm-platform

public void setKeepAliveTime(long time, TimeUnit unit) {
 threadPoolExecutor.setKeepAliveTime(time, unit);
}

代码示例来源:origin: stackoverflow.com

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.setKeepAliveTime(1, TimeUnit.MINUTES);
executor.allowCoreThreadTimeOut(true);
for (long i = 0; i < 1000; i++) {
  executor.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
    }
  }, 0, 1, TimeUnit.NANOSECONDS);
}

代码示例来源:origin: eclipse/smarthome

/**
 * Returns an instance of a cached thread pool service. If it is the first request for the given pool name, the
 * instance is newly created.
 *
 * @param poolName a short name used to identify the pool, e.g. "discovery"
 * @return an instance to use
 */
public static ExecutorService getPool(String poolName) {
  ExecutorService pool = pools.get(poolName);
  if (pool == null) {
    synchronized (pools) {
      // do a double check if it is still null or if another thread might have created it meanwhile
      pool = pools.get(poolName);
      if (pool == null) {
        int cfg = getConfig(poolName);
        pool = QueueingThreadPoolExecutor.createInstance(poolName, cfg);
        ((ThreadPoolExecutor) pool).setKeepAliveTime(THREAD_TIMEOUT, TimeUnit.SECONDS);
        ((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
        pools.put(poolName, pool);
        LOGGER.debug("Created thread pool '{}' with size {}", new Object[] { poolName, cfg });
      }
    }
  }
  return pool;
}

代码示例来源:origin: palantir/atlasdb

/**
 * Creates a fixed thread pool.
 *
 * @param threadNamePrefix thread name prefix
 * @param poolSize fixed thread pool size
 * @return a new fixed size thread pool with a keep alive time of 1 minute
 */
protected static ExecutorService createFixedThreadPool(String threadNamePrefix, int poolSize) {
  ThreadPoolExecutor executor = PTExecutors.newFixedThreadPool(poolSize,
      new NamedThreadFactory(threadNamePrefix, false));
  executor.setKeepAliveTime(1, TimeUnit.MINUTES);
  return executor;
}

代码示例来源:origin: eclipse/smarthome

/**
 * Returns an instance of a scheduled thread pool service. If it is the first request for the given pool name, the
 * instance is newly created.
 *
 * @param poolName a short name used to identify the pool, e.g. "discovery"
 * @return an instance to use
 */
public static ScheduledExecutorService getScheduledPool(String poolName) {
  ExecutorService pool = pools.get(poolName);
  if (pool == null) {
    synchronized (pools) {
      // do a double check if it is still null or if another thread might have created it meanwhile
      pool = pools.get(poolName);
      if (pool == null) {
        int cfg = getConfig(poolName);
        pool = new WrappedScheduledExecutorService(cfg, new NamedThreadFactory(poolName));
        ((ThreadPoolExecutor) pool).setKeepAliveTime(THREAD_TIMEOUT, TimeUnit.SECONDS);
        ((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
        ((ScheduledThreadPoolExecutor)pool).setRemoveOnCancelPolicy(true);
        pools.put(poolName, pool);
        LOGGER.debug("Created scheduled thread pool '{}' of size {}", new Object[] { poolName, cfg });
      }
    }
  }
  if (pool instanceof ScheduledExecutorService) {
    return (ScheduledExecutorService) pool;
  } else {
    throw new IllegalArgumentException("Pool " + poolName + " is not a scheduled pool!");
  }
}

代码示例来源:origin: apache/cloudstack

public void processStartupAnswer(final Answer answer, final Response response, final Link link) {
  boolean cancelled = false;
  synchronized (this) {
    if (_startup != null) {
      _startup.cancel();
      _startup = null;
    } else {
      cancelled = true;
    }
  }
  final StartupAnswer startup = (StartupAnswer)answer;
  if (!startup.getResult()) {
    s_logger.error("Not allowed to connect to the server: " + answer.getDetails());
    System.exit(1);
  }
  if (cancelled) {
    s_logger.warn("Threw away a startup answer because we're reconnecting.");
    return;
  }
  s_logger.info("Proccess agent startup answer, agent id = " + startup.getHostId());
  setId(startup.getHostId());
  _pingInterval = (long)startup.getPingInterval() * 1000; // change to ms.
  setLastPingResponseTime();
  scheduleWatch(link, response, _pingInterval, _pingInterval);
  _ugentTaskPool.setKeepAliveTime(2 * _pingInterval, TimeUnit.MILLISECONDS);
  s_logger.info("Startup Response Received: agent id = " + getId());
}

代码示例来源:origin: apache/activemq-artemis

public void setThreadPoolKeepAliveTime(long time) {
  thread_pool_keep_alive_time=time;
  if(thread_pool instanceof ThreadPoolExecutor)
    ((ThreadPoolExecutor)thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: apache/activemq-artemis

public void setOOBThreadPoolKeepAliveTime(long time) {
  oob_thread_pool_keep_alive_time=time;
  if(oob_thread_pool instanceof ThreadPoolExecutor)
    ((ThreadPoolExecutor)oob_thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: apache/activemq-artemis

@Property(name="thread_pool.keep_alive_time",description="Timeout in milliseconds to remove idle thread from regular pool")
public void setThreadPoolKeepAliveTime(long time) {
  thread_pool_keep_alive_time=time;
  if(thread_pool instanceof ThreadPoolExecutor)
    ((ThreadPoolExecutor)thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS);
}

相关文章

ThreadPoolExecutor类方法