Why is creating a Thread said to be expensive?

前端 未结 6 2183
遇见更好的自我
遇见更好的自我 2020-11-22 09:34

The Java tutorials say that creating a Thread is expensive. But why exactly is it expensive? What exactly is happening when a Java Thread is created that makes its creation

6条回答
  •  感动是毒
    2020-11-22 10:32

    There are two kinds of threads:

    1. Proper threads: these are abstractions around the underlying operating system's threading facilities. Thread creation is, therefore, as expensive as the system's -- there's always an overhead.

    2. "Green" threads: created and scheduled by the JVM, these are cheaper, but no proper paralellism occurs. These behave like threads, but are executed within the JVM thread in the OS. They are not often used, to my knowledge.

    The biggest factor I can think of in the thread-creation overhead, is the stack-size you have defined for your threads. Thread stack-size can be passed as a parameter when running the VM.

    Other than that, thread creation is mostly OS-dependent, and even VM-implementation-dependent.

    Now, let me point something out: creating threads is expensive if you're planning on firing 2000 threads per second, every second of your runtime. The JVM is not designed to handle that. If you'll have a couple of stable workers that won't be fired and killed over and over, relax.

提交回复
热议问题