views:

142

answers:

3

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.

  • Does every thread create their own instance of the jvm to handle their particular execution?
  • If not then does the jvm have to have some way to schedule which thread it will handle next, if so wouldn't this render the multi-threaded nature of java useless since only one thread can be ran at a time?
A: 

Java threads are mapped to native OS threads. They have little to do with the JVM itself.

Bozhidar Batsov
+1  A: 

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

No, your application running in the JVM can have many threads that all exist within that instance of the JVM.

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

Yes, the JVM has a thread scheduler. There are many different algorithms for thread scheduling, and which one is used is JVM-vendor dependent. (Scheduling in general is an interesting topic.)

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

I'm not sure I understand this part of your question. This is kind of the point of threading. You typically have more threads than CPUs, and you want to run more than one thing at a time. Threading allows you to take full(er) advantage of your CPU by making sure it's busy processing one thread while another is waiting on I/O, or is for some other reason not busy.

Bill the Lizard
+3  A: 

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 class attributes.

If not then does the jvm have to have some way to schedule which thread it will handle next, if so wouldn't this render the multi-threaded nature of java useless since only one thread can be ran at a time?

There are two kinds if thread implementation in Java. Native threads are mapped onto a thread abstraction that 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. Green thread implementations are no longer supported by Sun JVMs, AFAIK.

Stephen C