What is JVM?
JVM is a program or Virtual Machine that provides a run-time environment in which Java bytecode can be executed. JVMs are available for many software and hardware platforms. The same bytecode can be used on all JVMs for all platforms which makes Java platform independent.
JVM diagram:
JVM details:
1. Class loader subsystem:
It is a part of JVM which is responsible for finding and loading of class files.
2. Class/method area:
It is a part of JVM that contains the information of types/classes loaded by the class loader. It also contains the static variable, method body, etc.
3. Heap:
It is a part of JVM that contains objects. When a new object is created, memory is allocated to the object from the heap and the object is no longer referenced memory is reclaimed by the garbage collector.
4. Java Stack:
It is a part of JVM that contains local variables, operands, and frames. To operate, Byte code instructions take operands from the stack, operate them, and then return the result to the Java stack.
5. Program Counter:
For each thread JVM instance provides a separate program counter (PC) or PC register which contains the address of the currently executed instruction.
6. Native method stack:
Java programs can call native methods (A method written in another language like c). The native method stack contains these native methods.
7. Execution Engine:
It is a part of JVM that uses a Virtual processor (for execution), interpreter (for reading instructions), and JIT (Just in time) compiler (for performance improvement) to execute the instructions.
How JVM is created(Why JVM is virtual):
When JRE is installed on your machine, you get all the required code to create JVM. JVM is created when you run a Java program, e.g. If you create a Java program named FirstJavaProgram.java. To compile use – java FirstJavaProgram.java and to execute use – java FirstJavaProgram. When you run the second command – java FirstJavaProgram, JVM is created. That’s why it is virtual.
Lifetime of JVM:
When an application starts, a runtime instance is created. When the application ends, the runtime environment is destroyed. If n no. of applications starts on one machine then n no. of runtime instances are created and every application runs on its own JVM instance.
The main task of JVM:
- Search and locate the required files.
- Convert byte code into executable code.
- Allocate the memory into the ram
- Execute the code.
- Delete the executable code.