public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Use LinkedBlockingQueue, But does ConcurrentLinkedQueue should be more efficient , which is no-blocking and lock free?
The answer is simple: ConcurrentLinkedQueue
is not a BlockingQueue
, but LinkedBlockingQueue
is. The ThreadPoolExecutor
constructors expect BlockingQueue
s, so that Executors
creates instances also with other implementations of BlockingQueue
, like SynchronousQueue
or ArrayBlokingQueue
(depending on the factory method you call in Executors
).
So, the more general question is: why BlockingQueue
and not a simple Queue
. And here the answer is again simple: the BlockingQueue
interface has more useful methods. E.g a method tell if an element could be inserted in the queue without violating the capacity restrictions (and without throwing Exception, check BlockingQueue.offer()
). Or some methods block if the queue has no elements (which again has a timed poll()
and not timed version take()
). So, if you would check the implementation of the ThreadPoolExecutor, you would see that it calls these convenient methods that miss in the Queue
interface.