Java Reference
In-Depth Information
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
threadTimeoutMag, threadTimeoutUnit,
queue,
threadFactory,
rejectHandler
);
This creates a bunch of variables cluttering your scope. The solution for that, of course, is to move things
into their own method. Given the sheer number of lines of code, this is probably a good idea. The lambda-
to-interface conversions can also be done in their own methods. The resulting code is in Listing 6-4. Note
that this code provides convenient extension points for subclasses: it's just another example of how cleaning
up hard-to-read code also results in better-structured code. This demonstrates the simplest way to tell a
good practice from a bad one: a bad practice has collateral damage; a good practice has collateral benefits.
Listing 6-4. ThreadPoolExecutor Creation and Using Lambdas Responsibly
protected ThreadFactory createThreadFactory() {
return r -> {
Thread t = new Thread(r);
t.setPriority(Thread.MAX_PRIORITY);
return t;
};
}
protected RejectedExecutionHandler createdRejectedExecutionHandler() {
return (rejected, executor) -> {
BlockingQueue<Runnable> fullQueue = executor.getQueue();
// Wait for the timeout
try {
boolean submitted = fullQueue.offer(rejected, 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
rejected.run();
// Next, execute another piece of work to be nice
// (This also slows down the producer thread and might break a deadlock.)
Runnable otherWork = fullQueue.poll();
if (otherWork != null) otherWork.run();
};
}
 
Search WWH ::




Custom Search