Java Code Examples for java.util.concurrent.ThreadPoolExecutor#setMaximumPoolSize()

The following examples show how to use java.util.concurrent.ThreadPoolExecutor#setMaximumPoolSize() . 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: ServiceManager.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 修改线程池
 *
 * @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);
    }
}
 
Example 2
Source File: AsyncZuulServlet.java    From s2g-zuul with MIT License 6 votes vote down vote up
@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
}
 
Example 3
Source File: AbstractTelService.java    From hasor with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source File: KanboardAPI.java    From Kandroid with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
 
Example 5
Source File: ThreadsApplication.java    From tutorials with MIT License 5 votes vote down vote up
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);
}
 
Example 6
Source File: ThreadPoolExecutorSubclassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 7
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 8
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 9
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 10
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: ThreadPoolManager.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
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;
            }
        }
    }
}
 
Example 12
Source File: ThreadPoolReSeter.java    From sumk with Apache License 2.0 5 votes vote down vote up
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);
		}
	}
}
 
Example 13
Source File: ThreadPoolExecutorSubclassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 14
Source File: ThreadPoolExecutorSubclassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 15
Source File: ThreadPoolExecutorSubclassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 16
Source File: ThreadPoolExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 17
Source File: ThreadPoolExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 18
Source File: ThreadPoolManager.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
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;
            }
        }
    }
}
 
Example 19
Source File: KanboardAPI.java    From Kandroid with GNU General Public License v3.0 5 votes vote down vote up
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);
    }
 
Example 20
Source File: ContainerBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@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);
    }
}