Creating ScheduledThreadPoolExecutor Using Executors

大兔子大兔子 提交于 2019-12-23 23:07:39

问题


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?


回答1:


The problem is that Executors.newSingleThreadScheduledExecutor(); actually doesn't return a ScheduledThreadPoolExecutor.

Source code in the Executors class:

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
}

The Delegated... classes (there's a DelegatedExecutorService too) are just passing all the calls to the underlying executor, the ScheduledThreadPoolExecutor in 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 (List and not ArrayList, ScheduledExecutorService and not ScheduledThreadPoolExecutor).

If you absolutely need functionality available in ScheduledThreadPoolExecutor and not in the ScheduledExecutorService, you could use the constructor of ScheduledThreadPoolExecutor to create an instance of it.




回答2:


You should only use the returned executor as a ScheduledExecutorService, rather than casting it to a ScheduledThreadPoolExecutor.

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();



回答3:


To simplify:

A class implementing an interface could have other methods and fields that the interface doesn't. In this case, the method returns the interface so you can't downcast this to the implementing class.



来源:https://stackoverflow.com/questions/10200230/creating-scheduledthreadpoolexecutor-using-executors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!