Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is idle thread taking CPU execute time in Java Executors?

When I have this code in an application:

Executors.newFixedThreadPool(4);

but I never use this thread pool. Will the idle threads consume CPU time? If so - why?

like image 324
Ryanqy Avatar asked May 05 '17 02:05

Ryanqy


2 Answers

No, these threads are created lazily, or 'on-demand'. As stated in the documentation (emphasis mine):

On-demand construction

By default, even core threads are initially created and started only when new tasks arrive

Java provides methods to override this default and allow for eager creation, namely prestartCoreThread and prestartAllCoreThreads.


Once threads are actually created, idle ones (generally) won't take CPU time as there is no reason for them to be scheduled on a core when they have no work to do.

They will still hold on to some memory however, for their stack and whatnot.

like image 193
River Avatar answered Sep 28 '22 04:09

River


The javadoc states:

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks.

This might lead to assume: we don't know exactly. But as the other answer clearly finds - we can know, and the implementation is actually fully lazy. Thus:

 ExecutorService service = Executors.newFixedThreadPool(4);

does not even cause a lot of setup. The implementation would be free to wait for any

 service.submit(...

to happen.

On the other hand, that thread pool could (theoretically) be created immediately, and also 4 OS threads could be created. If the later is the case, all those threads would be idle'ing, so they should not consume any CPU resources.

But of course, as Elliott is correctly pointing out, that initial step of creating the pool and (potentially) creating 1 to 4 threads requires CPU activity.

And of course: threads are a OS resource. So even when they "only exist" and do nothing; they have that "cost". Where again, it might depend on the OS if that could ever turn into a problem (like reaching some "maximum number of existing threads" limit).

Finally: as this got me curious, I had a look into the current Java8 source code (from newFixedThreadPoo() and ThreadPoolExcecutor() down into DefaultThreadFactory). If I am not mistaken: those constructors only prepare for thread creation.

So: the "current" implementation is "fully" lazy; and if you really only call newFixedThreadPool() without ever using the resulting ExecutorService ... nothing happens (in terms of new threads being created).

like image 33
GhostCat Avatar answered Sep 28 '22 04:09

GhostCat