Java Reference
In-Depth Information
That code is extremely hard to follow, especially if you did not just look up the constructor. The
problems here are threefold: first, there are too many arguments in the constructor, so it is hard to keep
straight what is supposed to do what; second, the multiple lambdas in the row create some deep nesting,
and make it hard to see where one lambda stops and another begins; third, the lambda implementations
themselves are very long, which makes it hard to see where the constructor ends and the following code
begins. These problems may seem obvious to the reader, but to the API designer and the writer, it's a very
natural path to this code. You will probably inadvertently write this code sometime soon.
The best practice is to only have one lambda per method call. Since any single-element interface is
prone to being made into a lambda, you should limit your methods to only have one of those. However, we
are dealing with a violation of this best practice, and since it is in the Java SDK, it is not likely to be fixed any
time soon. When working with legacy code, the solution to this problem is to use semantic variables: create
and assign them first, and then pass them into the constructor.
int processorCount =
Math.max(1, Runtime.getRuntime().availableProcessors());
int corePoolSize = processorCount;
int maxPoolSize = processorCount * 2 + 1;
long threadTimeoutMag = 1L;
TimeUnit threadTimeoutUnit = TimeUnit.SECONDS;
BlockingQueue<Runnable> queue =
new ArrayBlockingQueue<>(processorCount * 4 + 1);
ThreadFactory threadFactory = r -> {
Thread t = new Thread(r);
t.setPriority(Thread.MAX_PRIORITY);
return t;
};
RejectedExecutionHandler rejectHandler = (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