Java Reference
In-Depth Information
for this class. Each of those callbacks is an interface, which means that there are suddenly many places
where lambdas make your life much easier. It is, however, possible to have too much of a good thing. It is a
great example of the limits of lambdas to provide clarity.
The problem is that the ThreadPoolExecutor has this constructor:
public ThreadPoolExecutor( int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler )
The temptation in Java 8 is to want to provide the threadFactory and handler inline. Unfortunately that
leads to code that looks like this:
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
processorCount * 2 + 1,
1L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(processorCount * 4 + 1),
r -> {
Thread t = new Thread(r);
return t;
(rejected, executor) -> {
BlockingQueue<Runnable> fullQueue = executor.getQueue();
// Wait for the timeout
try {
boolean submitted = fullQueue.offer(
1L, TimeUnit.SECONDS
if (submitted) return;
} catch (InterruptedException e) {
// Fall through
// If we get here, the queue is well and truly full
// First, execute our work;
// Next, execute another piece of work to be nice
// (This slows down the producer thread & might break a deadlock.)
Runnable otherWork = fullQueue.poll();
if (otherWork != null);
Search WWH ::

Custom Search