tyhdefu
tyhdefu

Reputation: 90

Can't cast result of Executors.newSingleThreadExecutor() to ThreadPoolExecutor

On the ThreadPoolExecutor docs, (here), it says to use the Executors class to create common threads, I want to only have one thread, so I use Executors.newSingleThreadExecutor and cast it to ThreadPoolExecutor as I have seen other examples do, but this throws a java.lang.ClassCastException. Here is the minimalised code I have reproduced it with.

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Test {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();
    }
}

Upvotes: 3

Views: 2025

Answers (1)

t3rmian
t3rmian

Reputation: 661

In general, I would always look for some kind of contract definition before making such an expectation. The docs do not clearly say that the Executors.newSingleThreadExecutor() will return ThreadPoolExecutor type object. Moreover, such implementation (without the contract) could potentially be changed in the future.

In this case newSingleThreadExecutor() returns a ExecutorService which underneath is a ThreadPoolExecutor but wrapped in a FinalizableDelegatedExecutorService. This class is more or less a sibling of ThreadPoolExecutor and as such, cannot be cast to it. I guess it's done so that:

the returned executor is guaranteed not to be reconfigurable to use additional threads

Depending on what you want to achieve, you should consider either:
- using ExecutorService returned from newSingleThreadExecutor() instead of ThreadPoolExecutor;
- using newFixedThreadPool(1) to get ThreadPoolExecutor.

Upvotes: 3

Related Questions