I see it is surprise not only for me: ScheduledThreadPoolExecutor has a fixed threadpool size:
No. From http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html:
.... it acts as a fixed-sized pool using corePoolSize threads ...
Some other related links:
Why is there no scheduled cached thread pool provided by the Java Executors class?
http://coding.tocea.com/java/dmi_futile_attempt_to_change_maxpool_size_of_scheduled_thread_pool_executor/
Why does ScheduledThreadPoolExecutor only accept a fixed number of threads?
Have a look at test result:
public class AsyncExecutorTest {
private static final ScheduledThreadPoolExecutor SCH_EXECUTOR = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
private static final ExecutorService EXECUTOR = (ExecutorService) Executors.newCachedThreadPool();
public static final int NUMBER = 10;
@Test
public void testSubmit() throws Exception {
submit(EXECUTOR);
submit(SCH_EXECUTOR);
SCH_EXECUTOR.setMaximumPoolSize(100);
submit(SCH_EXECUTOR);
SCH_EXECUTOR.setCorePoolSize(100);
submit(SCH_EXECUTOR);
}
private void submit(ExecutorService exe) throws InterruptedException {
long start = System.currentTimeMillis();
final CountDownLatch cdt = new CountDownLatch(NUMBER);
for (int i = 0; i < NUMBER; i++) {
exe.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
cdt.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
cdt.await();
System.out.println(System.currentTimeMillis() - start);
}
}
1002
5004
5001
1006
Suggested solution is:
scheduledExecutor = new ScheduledThreadPoolExecutor(150); //max thread
scheduledExecutor.setKeepAliveTime(10, TimeUnit.SECONDS);
scheduledExecutor.allowCoreThreadTimeOut(true); // allow terminate core idle threads
From example can be seen that max thread pool size could be changed not by setMaxPoolSize but by setCorePoolSize