JVM Architecture is very important to understand for the programmer to optimize the jvm to the application. JVM loads, analyzes, interprets and executes the java bytecode class file. JVM is a specification that provides runtime environment in which java bytecode can be executed. JRE is the implementation of Java Virtual Machine (JVM). We can create one or more instance of JVM with single JRE.
When a Java virtual machine runs a program, it needs memory to store many things, including bytecodes and other information it extracts from loaded class files, objects the program instantiates, parameters to methods, return values, local variables, and intermediate results of computations.
The Java virtual machine organizes the memory it needs to execute a program into several runtime data areas. Some runtime data areas are shared among all of an application's threads and others are unique to individual threads.
Class Loader is a part of the Java Runtime Environment (JRE) that dynamically loads Java classes into the Java Virtual Machine (JVM).
The Heap :-
Whenever a class instance or array is created in a running Java application, the memory for the new object is allocated from a java heap as shown in above picture.
The Method Area :-
Inside a Java virtual machine instance, information about loaded types is stored in a logical area of memory called the method area.
When the Java virtual machine loads a type, it uses a class loader to locate the appropriate class file. The class loader reads in the class file--a linear stream of binary data--and passes it to the virtual machine.
The virtual machine extracts information about the type from the binary data and stores the information in the method area.
All threads share the same method area, so access to the method area's data structures must be designed to be thread-safe.
If two threads are attempting to find a class named Lava, for example, and Lava has not yet been loaded, only one thread should be allowed to load it while the other one waits.
The Java Stack :-
When a new thread is launched, the Java virtual machine creates a new Java stack for the thread. A Java stack stores a thread's state in discrete frames.
When a thread invokes a Java method, the virtual machine creates and pushes a new frame onto the thread's Java stack.
The Program Counter :-
Each thread of a running program has its own pc register, or program counter, which is created when the thread is started.
As a thread executes a Java method, the pc register contains the address of the current instruction being executed by the thread.
If a thread is executing a native method, the value of the pc register is undefined.
Native Method Stack :-
A running Java application may use other data areas created by or for native methods. This Native Method Stack comes into the picture when
a java application invokes the method define in operating system language. Java Application can call native method using Java Native Method invocation(JNI).