ADJ
ADJ

Reputation: 1300

Is this correct? ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);

Is this correct?

ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)          
                                        Executors.newFixedThreadPool(numThreads);

I am doing this, since if I typecast, I will get access to getActiveCount() and getQueue() methods. Eclipse is not flagging any error here, but I want to be sure that what I am doing is correct.

It's weird, actually, as ThreadPoolExecutor implements ExecutorService and I am casting ExecutorService to ThreadPoolExecutor.

Upvotes: 1

Views: 1732

Answers (3)

Robin
Robin

Reputation: 24272

Although I would normally agree with @Evgeniy for the reasons he has stated, it is actually OK in this specific case because the Javadoc for ThreadPoolExecutor specifically recommends using the factory methods for creating an instance.

I would consider this as a contractual obligation that these methods will return the expected ThreadPoolExecutor. I would not rely on looking at the source code, as that can change over time, but the explicit recommendation in the javadoc should be reliable.

From the javadoc for ThreadPoolExecutor

To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors.newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation), Executors.newFixedThreadPool(int) (fixed size thread pool) and Executors.newSingleThreadExecutor() (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:

Upvotes: 4

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

We know from Executors source code that Executors.newFixedThreadPool returns ThreadPoolExecutor but Executors API does not say so. Thus theoretically it's better to create a ThreadPoolExecutor instance directly with new.

Upvotes: 2

Horonchik
Horonchik

Reputation: 477

You can look at the source code of newFixedThreadPool and see that it returns ThreadPoolExecutor so the casting will not throw an exception, ofcourse if someone will change the implementation of "newFixedThreadPool" in the future, your code might not work.

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

Upvotes: 1

Related Questions