I am extremely confused as to why the following cast does not work:
ScheduledThreadPoolExecutor timeoutControl = (ScheduledThreadPoolExecutor) Executors.newSingleThreadScheduledExecutor();
ScheduledThreadPoolExecutor implements the ScheduledExecutorService. What’s the point of this Executors call if I can’t use it with an actual class.
Am I using it wrong (probably), could someone offer some guidance please?
The problem is that
Executors.newSingleThreadScheduledExecutor();actually doesn’t return aScheduledThreadPoolExecutor.Source code in the
Executorsclass:The
Delegated...classes (there’s aDelegatedExecutorServicetoo) are just passing all the calls to the underlying executor, theScheduledThreadPoolExecutorin this case. The comments in the code suggest that the whole point of these classes is to hide all the non-interface methods that the underlying executor might have.In any case, it is better practice anyway to use the interface rather than the class version of the object you are working on (
Listand notArrayList,ScheduledExecutorServiceand notScheduledThreadPoolExecutor).If you absolutely need functionality available in
ScheduledThreadPoolExecutorand not in theScheduledExecutorService, you could use the constructor ofScheduledThreadPoolExecutorto create an instance of it.