javamultithreadingjvm

Understanding java's native threads and the jvm


I understand that the jvm is itself an application that turns the bytecode of the java executable into native machine code, but when using native threads I have some questions that I just cannot seem to answer.


Solution

  • Does every thread create their own instance of the JVM to handle their particular execution?

    No. They execute in the same JVM so that (for example) they can share objects and values of static fields.


    If not then does the JVM have to have some way to schedule which thread it will handle next

    There are two kinds of thread implementation in Java. Native threads are mapped onto a thread abstraction which is implemented by the host OS. The OS takes care of native thread scheduling, and time slicing.

    The second kind of thread is "green threads". These are implemented and managed by the JVM itself, with the JVM implementing thread scheduling. Java green thread implementations have not been supported by Sun / Oracle JVMs since Java 1.2. (See Green Threads vs Non Green Threads)

    As of Java 21, JVMs also support "virtual threads". In effect, these share a native thread between multiple lightweight threads. See the following for more information:


    If so wouldn't this render the multi-threaded nature of Java useless since only one thread can be ran at a time?

    We are talking about green threads now, and this is of historic interest (only) from the Java perspective.

    But even with the pure green threads, you still get concurrency. Control is switched to another threads a thread blocks on an I/O operation, whick acquiring a lock, and so on. Furthermore, the JVM's runtime could implement periodic thread preemption so that a CPU intensive thread doesn't monopolize the (single) core to the exclusion of other threads