java 如何根據內存占用情況調整開線程的數量?
問題描述
問題解答
回答1:setMaximumPoolSize 是否動態有效看下jdk源碼不就知道了
/** * Sets the maximum allowed number of threads. This overrides any * value set in the constructor. If the new value is smaller than * the current value, excess existing threads will be * terminated when they next become idle. * * @param maximumPoolSize the new maximum * @throws IllegalArgumentException if the new maximum is * less than or equal to zero, or * less than the {@linkplain #getCorePoolSize core pool size} * @see #getMaximumPoolSize */ public void setMaximumPoolSize(int maximumPoolSize) {if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize) throw new IllegalArgumentException();final ReentrantLock mainLock = this.mainLock;mainLock.lock();try { int extra = this.maximumPoolSize - maximumPoolSize; this.maximumPoolSize = maximumPoolSize; if (extra > 0 && poolSize > maximumPoolSize) {try { Iterator<Worker> it = workers.iterator(); while (it.hasNext() && extra > 0 && poolSize > maximumPoolSize) {it.next().interruptIfIdle();--extra; }} catch (SecurityException ignore) { // Not an error; it is OK if the threads stay live} }} finally { mainLock.unlock();} }
execute方法:
/** * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current <tt>RejectedExecutionHandler</tt>. * * @param command the task to execute * @throws RejectedExecutionException at discretion of * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted * for execution * @throws NullPointerException if command is null */ public void execute(Runnable command) {if (command == null) throw new NullPointerException();if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) { if (runState == RUNNING && workQueue.offer(command)) {if (runState != RUNNING || poolSize == 0) ensureQueuedTaskHandled(command); } else if (!addIfUnderMaximumPoolSize(command))reject(command); // is shutdown or saturated} }
相關文章:
1. 我的html頁面一提交,網頁便顯示出了我的php代碼,求問是什么原因?2. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?3. node.js - node 客戶端socket一直報錯Error: read ECONNRESET,用php的socket沒問題哈。。4. django - 后臺返回的json數據經過Base64加密,獲取時用python如何解密~!5. 老哥們求助啊6. docker 17.03 怎么配置 registry mirror ?7. tp6表單令牌8. node.js - gulp文件監聽的問題9. 如何解決docker宿主機無法訪問容器中的服務?10. javascript - canvas 可以實現 PS 魔法橡皮擦的功能嗎?
