Are there many threads in a JVM application expensive?

I am currently studying actors in Scala. The book recommends using the react method instead of receive , as it allows the system to use fewer threads.

I read why creating a thread is expensive . But what are the reasons that after you have threads (which must be executed for the acting system in Scala after initialization), are they expensive around?

Is it mainly memory consumption? Or are there other reasons?

+7
source share
3 answers

Using many threads may be more expensive than you expected because:

  • each thread consumes memory outside the heap, which limits the number of threads that can be created at all for the JVM;
  • the transition from one thread to another consumes some processor time, therefore, if you have activity that can be performed in one thread, you will save processor cycles;
  • there is a JVM scheduler that has more work if there are more threads. The same applies to the base OS scheduler;
  • Finally, it makes no sense to use more threads than processors for CPU-related tasks, and it makes no sense to use more I / O threads than you have I / O (for example, network clients).
+10
source

Besides the memory overhead associated with a thread (which may or may not be small), having more threads around also usually means that there will be more items to consider when it comes time to choose which thread the next processor will receive.

Some operating systems / JVMs may also have limits on the number of threads that can exist simultaneously.

In the end, it is the accumulation of small overhead, which can ultimately take into account a lot. And none of this is specific to Java.

+2
source

Having threads around is not "expensive." Of course, it depends on what we are talking about here. I suspect billions of threads will be a problem. I think that in general, having a large number of threads is considered expensive, because you can do more parallel work, so the processor rises, memory rises, etc. But if they are managed correctly (for example, to protect system resources), this is normal. The JVM does not necessarily use native threads, so a Java thread does not necessarily map to OS native threads (for example, look at green threads, for example, or light threads). In my opinion, there are no indirect threading costs in the JVM. Cost comes from poor flow management and overuse of resources, carelessly assigning jobs to them.

+2
source

All Articles