Created
February 25, 2016 06:39
-
-
Save pfmiles/1b475435d72d5eccdeaa to your computer and use it in GitHub Desktop.
当线程池满且等待任务queue也满时,submit(task)会block的executor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.util.concurrent.ArrayBlockingQueue; | |
import java.util.concurrent.ThreadFactory; | |
import java.util.concurrent.ThreadPoolExecutor; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* 当线程池满且等待任务queue也满时,submit(task)会block的executor | |
* @author pf-miles Feb 25, 2016 1:51:39 PM | |
*/ | |
public class BlockingSubmissionExecutor extends ThreadPoolExecutor { | |
// 由于ThreadPoolExecutor中调用了workQueue的offer方法来加入task到队列,但offer方法天生不会block,这里将offer方法重写为block的put实现 | |
private static final class OfferBlockingQueue<E> extends ArrayBlockingQueue<E> { | |
private static final long serialVersionUID = -8186794176623972764L; | |
public OfferBlockingQueue(int capacity) { | |
super(capacity); | |
} | |
@Override | |
public boolean offer(E e) { | |
try { | |
put(e); | |
return true; | |
} catch (InterruptedException ie) { | |
Thread.currentThread().interrupt(); | |
} | |
return false; | |
} | |
} | |
public BlockingSubmissionExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, | |
TimeUnit unit, int taskQueueSize, ThreadFactory threadFactory) { | |
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new OfferBlockingQueue<Runnable>( | |
taskQueueSize), threadFactory); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment