Simple thread running cpu runtime in Java Executors?

When I have this code in my application:

Executors.newFixedThreadPool(4);

      

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

+3


source to share


2 answers


javadoc states:

Creates a thread pool that reuses a fixed number of threads working on a shared unbounded queue. At any time, in most cases, nThreads will be the active processing tasks.

This can lead to the fact that we do not know for sure. But as the other answer clearly finds, we can know and the implementation is actually full of laziness. Thus:

 ExecutorService service = Executors.newFixedThreadPool(4);

      

doesn't even call up a lot of settings. The implementation will be free to wait for anyone

 service.submit(...

      



...

On the other hand, this thread pool can (in theory) be created immediately, and 4 OS threads can also be created. If so, all of these threads will be idle, so they should not consume CPU resources.

But of course, as Elliott correctly points out, this initial step of pooling and (potentially) creating 1 to 4 threads requires CPU activity.

And, of course, threads are an OS resource. So even when they "exist" and do nothing; they have this "value". Where again, it may be OS dependent if it could ever turn into a problem (eg hitting some "maximum thread count" limit).

Finally: as I was wondering, I looked at the current Java8 source code (from newFixedThreadPoo () and ThreadPoolExcecutor () down to DefaultThreadFactory ). If I'm not mistaken: these constructors only prepare to create threads.

So: the "current" implementation is "completely" lazy; and if you really only call newFixedThreadPool()

without using the ExecutorService as a result ... nothing (in terms of creating new threads).

+2


source


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

Design on demand

By default, even main threads are initially created and run only when new tasks appear

Java provides methods to override this default and allows for interesting creation, namely prestartCoreThread

and prestartAllCoreThreads

.




When threads are actually created, idle (usually) will not take up CPU time, as there is no reason to schedule them on the kernel when they are out of work.

They will still cling to some memory, but their stack and something else is wrong.

+1


source







All Articles