Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the JVM or the underlying OS handle thread state changes

When I create a multi-threaded program and I use methods such as Wait or Signal to control threads among other things, does JVM control all the thread state changes or does the underlying OS have anything to do with it.

like image 236
Julian Avatar asked Dec 17 '09 08:12

Julian


People also ask

Does JVM manage threads?

In the native thread model, the JVM creates and manages Java threads. But it does so using the thread API library of the underlying operating system.

What are the states of process How are the threads handled?

The process can have the following states new, ready, running, waiting, terminated, and suspended. Thread: Thread is the segment of a process which means a process can have multiple threads and these multiple threads are contained within a process. A thread has three states: Running, Ready, and Blocked.

How many threads can a JVM handle?

4.2. On Windows machines, there's no limit specified for threads. Thus, we can create as many threads as we want, until our system runs out of available system memory.


2 Answers

It depends on the implementation of the JVM. Most modern JVM's (Suns HotSpot, Oracles JRockit, IBM VMs) will use the Operating system threading model as this will give the best performance.

Early implementations used green threads - The VM was modelling the threads using itself. This was typically used when the platform or operating system it was running on didn't support threading. For example, in Java 1.1, Green Threads were used on Solaris. At the time, the common pattern to use multiple cores/CPU's in Solaris was to use multiple processes - only later were threads added to the Operating System.

The Java Language Specification does not specify how Threads must be implemented but in general, if the OS has threading support, modern JVM's will use the OS implementation. When there is no support in the OS, for example on low end mobile phones or in a Java Card implementation for example, then Green Threads will be used by the runtime.

like image 63
Robert Christie Avatar answered Oct 20 '22 23:10

Robert Christie


In general, Java threads will map to OS threads and Java will make use of OS synchronisation primitives to implement synchronized/wait/signal/..., but the mapping is not as straightforward as you might think. In fact, the JVM uses some clever tricks to improve performance and implements as much of the synchronisation code itself (at least the uncontended case).

If you are really interested in the details, have a look at the JVM source code or at cmeerw.org/notes/java_sync.html which provides some overview of how Java's synchronisation primitives are implemented on Linux and Solaris.

like image 34
cmeerw Avatar answered Oct 20 '22 23:10

cmeerw