java maximumpoolsize,如果maximumPoolSize小于corePoolSize怎么办? Java 6中可能存在的错误?...
我遇到了Java 6的ThreadPoolExecutor一個奇怪的問題 . 我不時地動態更改了corePoolSize,我觀察到線程池沒有處理應該完成的任務 .
例如,如果我有4個corePoolSize并且隊列中有許多任務等待,那么執行程序最多處理3個,有時甚至是2個 .
在調查問題的時候,我注意到當我增加或減少corePoolSize時我從未改變過maxPoolSize . 從我的申請開始,它一直是1 .
從來沒有在Java的文檔中找到一個聲明,提到maxPoolSize的效果小于核心 .
然后當我檢查源代碼時,我注意到在costructor和setCorePoolSize方法中,它會檢查maximumPoolSize小于corePoolSize的位置,如果是這樣,則拋出illegalArgumentException . 看看下面的代碼 .
構造函數
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
設置最大池大小
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 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();
}
}
所以,顯然這是一個不受歡迎的情況 . 但是沒有檢查setCorePoolSize,導致maximumPoolSize最終小于corePoolSize,并且沒有記錄這種情況的影響 .
設置核心池大小
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 0)
throw new IllegalArgumentException();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
int extra = this.corePoolSize - corePoolSize;
this.corePoolSize = corePoolSize;
if (extra < 0) {
int n = workQueue.size(); // don't add more threads than tasks
while (extra++ < 0 && n-- > 0 && poolSize < corePoolSize) {
Thread t = addThread(null);
if (t == null)
break;
}
}
else if (extra > 0 && poolSize > corePoolSize) {
try {
Iterator it = workers.iterator();
while (it.hasNext() &&
extra-- > 0 &&
poolSize > corePoolSize &&
workQueue.remainingCapacity() == 0)
it.next().interruptIfIdle();
} catch (SecurityException ignore) {
// Not an error; it is OK if the threads stay live
}
}
} finally {
mainLock.unlock();
}
}
難道你不認為應該有一種機制阻止這種情況結束嗎?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java maximumpoolsize,如果maximumPoolSize小于corePoolSize怎么办? Java 6中可能存在的错误?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python制作自动回复脚本_pytho
- 下一篇: java poi excel 图表_Ja