In java-9 the new method completeOnTimeout
in the CompletableFuture
class was introduced:
public CompletableFuture<T> completeOnTimeout(T value, long timeout,
TimeUnit unit) {
if (unit == null)
throw new NullPointerException();
if (result == null)
whenComplete(new Canceller(Delayer.delay(
new DelayedCompleter<T>(this, value),
timeout, unit)));
return this;
}
What I do not understand is why it uses the static ScheduledThreadPoolExecutor
inside its implementation:
static ScheduledFuture<?> delay(Runnable command, long delay,
TimeUnit unit) {
return delayer.schedule(command, delay, unit);
}
Where
static final ScheduledThreadPoolExecutor delayer;
static {
(delayer = new ScheduledThreadPoolExecutor(
1, new DaemonThreadFactory())).
setRemoveOnCancelPolicy(true);
}
For me it is a very strange approach, as it can become a bottleneck for the whole application: the only one ScheduledThreadPoolExecutor
with the only one thread keeping inside the pool for all possible CompletableFuture
tasks?
What am I missing here?
P.S. It looks like:
authors of this code were reluctant to extract this logic and preferred to reuse the
ScheduledThreadPoolExecutor
,and this apparently leaded to a such solution with a static variable, because it is very inefficient to create a new executor for each
CompletableFuture
.
But my doubt still remains, as I find general approach strange.