I have some code that makes heavy use of a thread pool, which I use by creating Collection<Callable<T>> tasks, and calling ExecutorService.invokeAll(tasks).
for (Future<Object> future : threadPool.invokeAll(tasks)) {
Object object = future.get();
// Calling thread effectively blocks on invokeAll().
}
In my app, the size of tasks varies a lot. In fact, most of the time the ExecutorService.invokeAll() is called with a single task. The implementation of invokeAll() that I’m using calls ThreadPoolExecutor.execute(), whose implementation appears to always run the task in the thread pool (never in the calling thread).
In the case of a single task, would it be more efficient to call the task in the current thread rather than send it off to another thread?
Yes, it would be more efficient. That’s not an interesting question though. The interesting questions are how inefficient it is – which will depend on what your task is doing – and whether you’re doing this enough in your application for it to be significant overall.
We don’t have enough information to evaluate that for you. If you’re executing a single trivial task (“fetch a value from a map”) millions of times per second, then all the indirection via the thread pool could make a real difference. If your tasks actually do a significant amount of work, then it’s almost certainly not worth the extra code of special-casing the case where you’ve only got a single task.