下面列出了java.util.concurrent.ThreadPoolExecutor#setMaximumPoolSize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 修改线程池
*
* @param executor
* @param name
* @param parametric
* @param coreKey
* @param maxKey
*/
public static void updateThreadPool(final ThreadPoolExecutor executor, final String name, final Parametric parametric,
final String coreKey, final String maxKey) {
if (executor == null) {
return;
}
Integer core = parametric.getInteger(coreKey);
if (core != null && core > 0 && core != executor.getCorePoolSize()) {
logger.info(String.format("Core pool size of %s is changed from %d to %d",
name, executor.getCorePoolSize(), core));
executor.setCorePoolSize(core);
}
Integer max = parametric.getInteger(maxKey);
if (max != null && max > 0 && max != executor.getMaximumPoolSize()) {
logger.info(String.format("Maximum pool size of %s is changed from %d to %d",
name, executor.getMaximumPoolSize(), max));
executor.setMaximumPoolSize(max);
}
}
@Override
public void init() throws ServletException {
reNewThreadPool();
Runnable c = new Runnable() {
@Override
public void run() {
ThreadPoolExecutor p = poolExecutorRef.get();
p.setCorePoolSize(coreSize.get());
p.setMaximumPoolSize(maximumSize.get());
p.setKeepAliveTime(aliveTime.get(),TimeUnit.MILLISECONDS);
}
};
coreSize.addCallback(c);
maximumSize.addCallback(c);
aliveTime.addCallback(c);
// TODO metrics reporting
}
@Override
protected void doInitialize() {
// .触发SPI
logger.info("tConsole -> trigger TelStartContextListener.onStart");
this.spiTrigger.notifySpiWithoutResult(TelStartContextListener.class, listener -> {
listener.onStart(AbstractTelService.this);
});
//
logger.info("tConsole -> applyCommand.");
this.applyCommand();
this.addCommand(new String[] { "get", "set" }, new GetSetExecutor());
this.addCommand(new String[] { "quit", "exit" }, new QuitExecutor());
this.addCommand(new String[] { "help" }, new HelpExecutor());
//
// .执行线程池
String shortName = "tConsole-Work";
int workSize = 2;
this.executor = Executors.newScheduledThreadPool(workSize, new NameThreadFactory(shortName, this.classLoader));
ThreadPoolExecutor threadPool = (ThreadPoolExecutor) this.executor;
threadPool.setCorePoolSize(workSize);
threadPool.setMaximumPoolSize(workSize);
logger.info("tConsole -> create TelnetHandler , threadShortName={} , workThreadSize = {}.", shortName, workSize);
}
/**
* setMaximumPoolSize(int) throws IllegalArgumentException
* if given a value less the core pool size
*/
public void testMaximumPoolSizeIllegalArgumentException() {
final ThreadPoolExecutor p =
new CustomTPE(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
@Override
public void setStartStopThreads(int startStopThreads) {
this.startStopThreads = startStopThreads;
// Use local copies to ensure thread safety
ThreadPoolExecutor executor = startStopExecutor;
if (executor != null) {
int newThreads = getStartStopThreadsInternal();
executor.setMaximumPoolSize(newThreads);
executor.setCorePoolSize(newThreads);
}
}
public KanboardAPI(String serverURL, final String username, final String password) throws IOException {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
kanboardURL = KanboardAPI.sanitizeURL(serverURL.trim());
Log.i(Constants.TAG, String.format("Host uses %s", kanboardURL.getProtocol()));
// threadPoolExecutor = new ThreadPoolExecutor(12, 12, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(256));
threadPoolExecutor = (ThreadPoolExecutor) AsyncTask.THREAD_POOL_EXECUTOR;
threadPoolExecutor.setCorePoolSize(12);
threadPoolExecutor.setMaximumPoolSize(12);
}
protected void modified(Map<String, Object> properties) {
for (Entry<String, Object> entry : properties.entrySet()) {
if (entry.getKey().equals("service.pid") || entry.getKey().equals("component.id")
|| entry.getKey().equals("component.name")) {
continue;
}
String poolName = entry.getKey();
Object config = entry.getValue();
if (config == null) {
configs.remove(poolName);
}
if (config instanceof String) {
try {
Integer poolSize = Integer.valueOf((String) config);
configs.put(poolName, poolSize);
ThreadPoolExecutor pool = (ThreadPoolExecutor) pools.get(poolName);
if (pool instanceof ScheduledThreadPoolExecutor) {
pool.setCorePoolSize(poolSize);
LOGGER.debug("Updated scheduled thread pool '{}' to size {}",
new Object[] { poolName, poolSize });
} else if (pool instanceof QueueingThreadPoolExecutor) {
pool.setMaximumPoolSize(poolSize);
LOGGER.debug("Updated queuing thread pool '{}' to size {}",
new Object[] { poolName, poolSize });
}
} catch (NumberFormatException e) {
LOGGER.warn("Ignoring invalid configuration for pool '{}': {} - value must be an integer",
new Object[] { poolName, config });
continue;
}
}
}
}
/**
* setMaximumPoolSize(int) throws IllegalArgumentException if
* given a value less the core pool size
*/
public void testMaximumPoolSizeIllegalArgumentException() {
final ThreadPoolExecutor p =
new ThreadPoolExecutor(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
/**
* setMaximumPoolSize throws IllegalArgumentException
* if given a negative value
*/
public void testMaximumPoolSizeIllegalArgumentException2() {
final ThreadPoolExecutor p =
new ThreadPoolExecutor(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(-1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
/**
* getMaximumPoolSize returns value given in constructor if not
* otherwise set
*/
public void testGetMaximumPoolSize() {
final ThreadPoolExecutor p =
new CustomTPE(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
assertEquals(3, p.getMaximumPoolSize());
p.setMaximumPoolSize(5);
assertEquals(5, p.getMaximumPoolSize());
p.setMaximumPoolSize(4);
assertEquals(4, p.getMaximumPoolSize());
}
}
/**
* setMaximumPoolSize(int) throws IllegalArgumentException
* if given a value less the core pool size
*/
public void testMaximumPoolSizeIllegalArgumentException() {
final ThreadPoolExecutor p =
new CustomTPE(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
/**
* setMaximumPoolSize throws IllegalArgumentException
* if given a negative value
*/
public void testMaximumPoolSizeIllegalArgumentException2() {
final ThreadPoolExecutor p =
new CustomTPE(2, 3,
LONG_DELAY_MS,
MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(-1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
private void resetThreadPoolSize() {
if (!ThreadPoolExecutor.class.isInstance(SumkThreadPool.executor())) {
return;
}
ThreadPoolExecutor pool = (ThreadPoolExecutor) SumkThreadPool.executor();
int size = AppInfo.getInt("sumk.core.threadpool.core", 0);
if (size > 0 && pool.getCorePoolSize() != size) {
logger.info("change ThreadPool size from {} to {}", pool.getCorePoolSize(), size);
pool.setCorePoolSize(size);
}
size = AppInfo.getInt("sumk.core.threadpool.max", 0);
if (size > 0 && pool.getMaximumPoolSize() != size) {
logger.info("change ThreadPool max size from {} to {}", pool.getMaximumPoolSize(), size);
pool.setMaximumPoolSize(size);
}
size = AppInfo.getInt("sumk.core.threadpool.aliveTime", 0);
if (size > 0 && pool.getKeepAliveTime(TimeUnit.MILLISECONDS) != size) {
logger.info("change ThreadPool keepalive time from {} to {}", pool.getKeepAliveTime(TimeUnit.MILLISECONDS),
size);
pool.setKeepAliveTime(size, TimeUnit.MILLISECONDS);
}
String v = AppInfo.get("sumk.core.threadpool.allowCoreThreadTimeOut", null);
if (v != null) {
boolean allowCoreTimeout = "1".equals(v) || "true".equalsIgnoreCase(v);
if (allowCoreTimeout != pool.allowsCoreThreadTimeOut()) {
logger.info("change ThreadPool allowsCoreThreadTimeOut from {} to {}", pool.allowsCoreThreadTimeOut(),
allowCoreTimeout);
pool.allowCoreThreadTimeOut(allowCoreTimeout);
}
}
}
public KanboardAPI(String serverURL, final String username, final String password) throws IOException {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
kanboardURL = KanboardAPI.sanitizeURL(serverURL.trim());
Log.i(Constants.TAG, String.format("Host uses %s", kanboardURL.getProtocol()));
// threadPoolExecutor = new ThreadPoolExecutor(12, 12, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(256));
threadPoolExecutor = (ThreadPoolExecutor) AsyncTask.THREAD_POOL_EXECUTOR;
threadPoolExecutor.setCorePoolSize(12);
threadPoolExecutor.setMaximumPoolSize(12);
}
protected void modified(Map<String, Object> properties) {
for (Entry<String, Object> entry : properties.entrySet()) {
if (Constants.SERVICE_PID.equals(entry.getKey()) || ComponentConstants.COMPONENT_ID.equals(entry.getKey())
|| ComponentConstants.COMPONENT_NAME.equals(entry.getKey())) {
continue;
}
String poolName = entry.getKey();
Object config = entry.getValue();
if (config == null) {
configs.remove(poolName);
}
if (config instanceof String) {
try {
Integer poolSize = Integer.valueOf((String) config);
configs.put(poolName, poolSize);
ThreadPoolExecutor pool = (ThreadPoolExecutor) pools.get(poolName);
if (pool instanceof ScheduledThreadPoolExecutor) {
pool.setCorePoolSize(poolSize);
LOGGER.debug("Updated scheduled thread pool '{}' to size {}", poolName, poolSize);
} else if (pool instanceof QueueingThreadPoolExecutor) {
pool.setMaximumPoolSize(poolSize);
LOGGER.debug("Updated queuing thread pool '{}' to size {}", poolName, poolSize);
}
} catch (NumberFormatException e) {
LOGGER.warn("Ignoring invalid configuration for pool '{}': {} - value must be an integer", poolName,
config);
continue;
}
}
}
}
public void testCorePoolSizeGreaterThanMax() {
ThreadPoolExecutor tp = new ThreadPoolExecutor(
1 /* core pool size */, 1 /* max pool size */,
1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10));
// It should be illegal to set a core pool size that's larger than the max
// pool size but apps have been allowed to get away with it so far. The pattern
// below occurs in a commonly used library. Note that the executor is in a sane
// state at the end of both method calls.
tp.setCorePoolSize(5);
tp.setMaximumPoolSize(5);
}
/**
* getMaximumPoolSize returns value given in constructor if not
* otherwise set
*/
public void testGetMaximumPoolSize() {
final ThreadPoolExecutor p =
new ThreadPoolExecutor(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
assertEquals(3, p.getMaximumPoolSize());
p.setMaximumPoolSize(5);
assertEquals(5, p.getMaximumPoolSize());
p.setMaximumPoolSize(4);
assertEquals(4, p.getMaximumPoolSize());
}
}
/**
* setMaximumPoolSize(int) throws IllegalArgumentException if
* given a value less the core pool size
*/
public void testMaximumPoolSizeIllegalArgumentException() {
final ThreadPoolExecutor p =
new ThreadPoolExecutor(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
/**
* setMaximumPoolSize throws IllegalArgumentException
* if given a negative value
*/
public void testMaximumPoolSizeIllegalArgumentException2() {
final ThreadPoolExecutor p =
new ThreadPoolExecutor(2, 3,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
try {
p.setMaximumPoolSize(-1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
public static void testThreadPoolExecutor() {
ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
executor.setMaximumPoolSize(8);
ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
}