The Wayback Machine - https://web.archive.org/web/20240912221619/https://www.geeksforgeeks.org/jvm-works-jvm-architecture/
Open In App

How JVM Works – JVM Architecture

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe the whole JVM. 

Class Loader Sub System

1. Class Loader Subsystem

It is mainly responsible for three activities. 

  • Loading
  • Linking
  • Initialization

Loading:

The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method area. For each “.class” file, JVM stores the following information in the method area.

  • The fully qualified name of the loaded class and its immediate parent class.
  • Whether the “.class” file is related to Class or Interface or Enum.
  • Modifier, Variables and Method information etc.

After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap memory. Please note that this object is of type Class predefined in java.lang package. These Class object can be used by the programmer for getting class level information like the name of the class, parent name, methods and variable information etc. To get this object reference we can use getClass() method of Object class.

Java
// A Java program to demonstrate working
// of a Class type object created by JVM
// to represent .class file in memory.
import java.lang.reflect.Field;
import java.lang.reflect.Method;

// Java code to demonstrate use
// of Class object created by JVM
public class Test {
    public static void main(String[] args)
    {
        Student s1 = new Student();

        // Getting hold of Class
        // object created by JVM.
        Class c1 = s1.getClass();

        // Printing type of object using c1.
        System.out.println(c1.getName());

        // getting all methods in an array
        Method m[] = c1.getDeclaredMethods();
        for (Method method : m)
            System.out.println(method.getName());

        // getting all fields in an array
        Field f[] = c1.getDeclaredFields();
        for (Field field : f)
            System.out.println(field.getName());
    }
}

// A sample class whose information
// is fetched above using its Class object.
class Student {
    private String name;
    private int roll_No;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getRoll_no() { return roll_No; }
    public void setRoll_no(int roll_no)
    {
        this.roll_No = roll_no;
    }
}

Output
Student
getName
setName
getRoll_no
setRoll_no
name
roll_No

Note: For every loaded “.class” file, only one object of the class is created.

Student s2 = new Student();
// c2 will point to same object where
// c1 is pointing
Class c2 = s2.getClass();
System.out.println(c1==c2); // true

Linking

Performs verification, preparation, and (optionally) resolution.

  • Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly formatted and generated by a valid compiler or not. If verification fails, we get run-time exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once this activity is completed then the class file is ready for compilation.
  • Preparation: JVM allocates memory for class static variables and initializing the memory to default values. 
  • Resolution: It is the process of replacing symbolic references from the type with direct references. It is done by searching into the method area to locate the referenced entity.

Initialization

In this phase, all static variables are assigned with their values defined in the code and static block(if any). This is executed from top to bottom in a class and from parent to child in the class hierarchy. In general, there are three class loaders:  

  • Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of loading trusted classes. It loads core java API classes present in the “JAVA_HOME/lib” directory. This path is popularly known as the bootstrap path. It is implemented in native languages like C, C++.
  • Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in the extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified by the java.ext.dirs system property. It is implemented in java by the sun.misc.Launcher$ExtClassLoader class.
  • System/Application class loader: It is a child of the extension class loader. It is responsible to load classes from the application classpath. It internally uses Environment Variable which mapped to java.class.path. It is also implemented in Java by the sun.misc.Launcher$AppClassLoader class.
Java
// Java code to demonstrate Class Loader subsystem
public class Test {
    public static void main(String[] args)
    {
        // String class is loaded by bootstrap loader, and
        // bootstrap loader is not Java object, hence null
        System.out.println(String.class.getClassLoader());

        // Test class is loaded by Application loader
        System.out.println(Test.class.getClassLoader());
    }
}

Output
null
jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f

Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load request to extension class loader and extension class loader delegate request to the bootstrap class loader. If a class found in the boot-strap path, the class is loaded otherwise request again transfers to the extension class loader and then to the system class loader. At last, if the system class loader fails to load class, then we get run-time exception java.lang.ClassNotFoundException. 

2. Class Loaders

There are three primary types of class loaders:

  • Bootstrap Class Loader: Loads core Java API classes from the JAVA_HOME/lib directory. It is implemented in native code and is not a Java object.
  • Extension Class Loader: Loads classes from the JAVA_HOME/jre/lib/ext directory or any directory specified by the java.ext.dirs system property. It is implemented in Java.
  • System/Application Class Loader: Loads classes from the application classpath, which is specified by the java.class.path environment variable. It is also implemented in Java.
Class Loaders

Example:

public class Test {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader());
System.out.println(Test.class.getClassLoader());
}
}

3. JVM Memory Areas

  • Method area: In the method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource. 
  • Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is also a shared resource.
  • Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which stores methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.
  • PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate PC Registers.
  • Native method stacks: For every thread, a separate native stack is created. It stores native method information. 
JVM Memory Area

4. Execution Engine 

Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and information present in various memory area and executes instructions. It can be classified into three parts:

  • Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that when one method is called multiple times, every time interpretation is required.
  • Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the entire bytecode and changes it to native code so whenever the interpreter sees repeated method calls, JIT provides direct native code for that part so re-interpretation is not required, thus efficiency is improved.
  • Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector, refer Garbage Collector.

5. Java Native Interface (JNI)

It is an interface that interacts with the Native Method Libraries and provides the native libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may be specific to hardware.

6. Native Method Libraries

These are collections of native libraries required for executing native methods. They include libraries written in languages like C and C++.

For more information refer to this YouTube video link: How Java Works?



Previous Article
Next Article

Similar Reads

Verification in Java (JVM)
After the class loader in the JVM loads the byte code of .class file to the machine the Bytecode is first checked for validity by the verifier and this process is called as verification. The verifier performs as much checking as possible at the Linking so that expensive operation performed by the interpreter at the run time can be eliminated. It en
3 min read
Java Virtual Machine (JVM) Stack Area
For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may be termed as Run – Time Stack. Every method call pe
4 min read
Types of JVM Garbage Collectors in Java with implementation details
prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To deallocate unused memory, Garbage collector track
5 min read
How to Generate JVM Heap Memory Dump?
Java Heap dump is a snapshot of all java objects that are present in the JVM(Java Virtual Machine) at a certain point in time. The JVM allocates memory for objects which are class instances or arrays in the heap memory. When the objects are no longer needed or are no more referenced, the Garbage Collector runs and reclaims the memory space occupied
7 min read
Difference Between JVM and DVM
JVM is the virtual machine that runs java code on different platforms. It acts as an abstract layer between the program and the platform on which the java code is running. The portability of Java code is possible only because of the JVM. The javac compiler converts the source code file(.java file) into an intermediate java bytecode format which is
3 min read
Difference between JIT and JVM in Java
Java Virtual Machine (JVM) is used in the java runtime environment(JRE). The original JVM was conceived as a bytecode interpreter. This may come as a bit of a surprise because of performance problems. Many modern languages are meant to be compiled into CPU-specific, executable code. The fact that the JVM executes a Java program, however, helps addr
4 min read
Frequently Used JVM Parameters
A JVM or Java Virtual Machine is a software implementation of a physical machine, or we can say it is an abstract machine. Java was designed with the concept of WORA (Write Once Run Anywhere), which runs on a VM. It is a specification that gives a runtime environment during which java bytecode is often executed. The compiler compiles the Java file
3 min read
Difference Between 32-bit and 64-bit JVM in Java
One does not need to know the difference unless developing a performance-critical application. The minor distinction between 32-bit and 64-bit JVMs would make little difference in your application. Now coming onto the differences where we will be listing out some key differences between 32-bit and 64-bit Java Virtual Machines are listed below in wh
4 min read
Different Ways to Collect Garbage in Java HotSpot JVM
JDKs come with different JVM implementations (Oracle HotSpot, Eclipse OpenJ9, GraalVM, Jikes RVM, Codename One), and different garbage collector implementations with different tuning options (Serial, Parallel, CMS, G1, Z, Shenandoah). In this article, we will know more about the Garbage Collector, how it works, and the various types of GC available
7 min read
Does JVM create object of Main class (the class with main())?
Consider following program. class Main { public static void main(String args[]) { System.out.println("Hello"); } } Output: Hello Does JVM create an object of class Main? The answer is "No". We have studied that the reason for main() static in Java is to make sure that the main() can be called without any instance. To justify the same, we
1 min read
JVM Shutdown Hook in Java
Shutdown Hooks are a special construct that allows developers to plug in a piece of code to be executed when the JVM is shutting down. This comes in handy in cases where we need to do special clean up operations in case the VM is shutting down.Handling this using the general constructs such as making sure that we call a special procedure before the
6 min read
Differences between JDK, JRE and JVM
Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java development. Now we need an environment to make a
5 min read
How many types of memory areas are allocated by JVM?
JVM (Java Virtual Machine) is an abstract machine, In other words, it is a program/software which takes Java bytecode and converts the byte code (line by line) into machine understandable code.  JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in Java code. JVM
3 min read
Introduction to Java Mission Control for JVM Monitoring
Java Mission Control (JMC) is a powerful monitoring, diagnostics, and performance analysis tool. Oracle provides this to run the Java applications on the Java Virtual Machine. It is part of the Java Development Kit and offers developers and administrators insights into the runtime behaviour of Java applications. The JMC is useful for identifying pe
5 min read
How HashTable Works Internally in Java?
Hashtable is a kind of Hash map but is synchronized. Hash map is non–synchronized, permits one null key & multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, the key/values pairs are stored in Hashtable. The Hash table does not allow null value/key. When using this you specify an object t
11 min read
How Jackson Data Binding Works in Spring Boot?
Spring is a framework of java that is used to build high-level, large-scale enterprise applications. And the most common thing we do in almost every application is transfer data between the front-end and back-end (to the server). Supposedly, when we perform Update, Create, or any other operation that impacts changes in the Database then what happen
4 min read
How compare() method works in Java
Prerequisite: Comparator Interface in Java, TreeSet in JavaThe compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y)-1: if (x < y)1: if (x > y)Syntax: public int compare(Object obj1, Object obj2)where obj1 and obj2 are the two objects to be compared using compare() method.
3 min read
Spring Boot - How Thymeleaf Works?
Thymeleaf is a Java library, and template engine used to parse and render the data produced by the application to template files - thus providing transformation. It is just like HTML but is provided with more attributes for working with rendered data. It allows caching of the parsed data/file to increase efficiency while in production. Types of tem
4 min read
Java Architecture for XML Binding ( JAXB ) | Set-1
Java Architecture for XML Binding (JAXB) defines an API for reading and writing Java objects to and from XML documents. JAXB gives Java developers an efficient and standard way of mapping between XML and Java code. JAXB makes it easier for developers to extend their applications with XML and Web Services technologies.At First JAXB was developed as
4 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
MVP (Model View Presenter) Architecture Pattern in Android with Example
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing
12 min read
MVVM (Model View ViewModel) Architecture Pattern in Android
Developers always prefer clean and structured code for projects. Organizing the codes according to a design pattern helps in the maintenance of the software. By having knowledge of all crucial logic parts of the android application, it is easier to add and remove app features. Further, design patterns also assure that all the codes get covered in U
7 min read
Overview of Data Binding in Android Architecture Components
This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you'll get one from GitHub. Then, attempt to use the MVVM components introduced during this article. In some ways, software development
4 min read
JSP Architecture
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier architecture. It has a Client, Web Server, and Database. The client is the web browser or application on the user side. Web Server uses a JSP Engine i.e; a container that processes JSP. For example, Apache Tomcat has a built-in JSP Engine. JSP Engine interc
3 min read
Android MVP Architecture Extension with Interactors and Repositories
Nature's truth is evolution, and new developments are led by natural selection. As a result, there are many diverse species with numerous similarities, and they all adapt best to their environment. The concept that one is superior to the other is only applicable under limited circumstances when one is more suited for survival. When the circumstance
5 min read
Build Modular Android App Architecture with Example
Modules are piece of code that is independently created and maintained and can be used in a different system. In Android apps modules can be a simple feature like Search or it may be purchased on demand. For eg. In gaming apps like PUBG, skins of the guns and the character are also a module. There are several modules namely they are, Application mo
4 min read
Spring Boot - Architecture
The Spring Boot is built on top of the core Spring framework. It is a simplified and automated version of the spring framework. The spring boot follows a layered architecture in which each layer communicates to other layers(Above or below in hierarchical order). The spring boot documentation provides the following definition to the Spring Boot Fram
2 min read
Spring Security Architecture
Spring Security framework adds two important capabilities to web applications, Authentication Authorization/Access Control This framework provides protection against popular security issues like SCRF attacks, or Fixation attacks. It provides a secure and standard way to set up user login functionality in web applications and thus provides quick use
2 min read
Spring Framework Architecture
The Spring framework is a widely-used open-source Java framework that provides a comprehensive programming and configuration model for building enterprise applications. Its architecture is designed around two core principles: Dependency Injection (DI) and Aspect-Oriented Programming (AOP). The Spring framework consists of several modules, which can
7 min read
What are the Deployment Challenges in Monolithic Architecture?
Monolithic Architecture is like a big container, where all the software components of an app are created and tightly coupled, that is each component is fully dependent on the other. For example, you are developing an e-commerce site and there any many modules in it like the below image. As you can see in the example all the services provided by the
5 min read
Article Tags :
Practice Tags :