JVM ARCHITECTURE

JVM--Java Virtual machine

1. what is virtual machine?
Virtual means physically doesn't existence.
it is a software simulation of a machine. which can perform operations like a physical machine.
which is not having physical existence.


2. Types of Virtual Machines?what is the purpose of each machine?
all virtual machines are categorized into two categories
               i. hardware based VM/System Based VM
              ii. application based VM/process based VM/Software Based VM

i. Hardware based VM:
  KVM[kernal based virtual machine], VM Ware[virtual machine Ware], cloud computing,Xen
  Ex: Linux os
  on the same physical machine we can create several logical machines with strong isolation from each   other.
 adv: effective utilization of resources.
 this type of Hardware based VM associated with Admin roles. Programmers never associated with  hardware based VM

ii. Application based VM:
  this VM acts as runtime engines to run a particular programming language applications.
   ex: JVM used to run java programs
        PVM [parrot virtual machine] to run pearl based applications
        CLR[Common Language runtime] to run .Net based programs
     
3. Basic Architecture Diagram of JVM?
  JVM is part of JRE which is the part of JDK. it acts as a runtime engine to run java based            applications. it is the responsible to   load .class file and run line by line. it is an interpreter.
   important components Class Loader, Memory Area, Execution Engine

  • Class Loader subsystem loads .class files and stores in memory area[method area]
  • Execution engine is responsible to run the .class file line by line.




  • Method area contains .class file
  • Heap Area contains objects
  • Stack Area: 
  • PC registers:current executing instruction address
  • Native method stacks:
  • Native method Libraries: methods which are not implemented in java
    Ex: hashCode(), clone()
  • So Java native Interface : provides information about the Native libraries information to JVM    
4. Class Loader Subsystem?

      i. loading
    ii. Linking
    iii. initialization

Class Loader subsystem is responsible for loading .class files.includes three activities
loading, linking, initialization.
i. Loading : read the .class file from local machine and store corresponding binary data in the method area of JVM.
The method area contains: fully qualified name of class,fully qualified name of  immediate parent, weather .class file represents class/interface/enum,methods information, variables information, modifiers information, constant pool information,constructors, total .class file complete information etc.
After loading every .class file JVM immediately create one java.lang.class Class object.to represent the total .class information in the heap area. programmer use this Class object to get Class level information.ex: names of all methods in a class.
ex: to print method information related to Student class by using corresponding Class Class Object.
Class Student{
private String name;
private int rollno;
public String getName()
{
return name;
}
public int getRollno()
{
return rollno;
}
}
Class Test{
public static void main(arg[] s)throws Exception{
Class c=Class.forName("Student");//loading student class file and getting class Class object to 'c'
//getting method information
Method[] m=c.getDeclaredMethods();
for(Method m1:m)
{
System.out.println(m1);//complete method prototype we will get
}
Field[] f=c.getDeclaredFields();
for(Field f1:f)
{
System.out.println(f1);//
}
}
}
here Method and Field are classes hence we need to import java.lang.reflect.*;
.class will be loaded once when ever we are calling it first time.So Jvm will create only one class Class object . even we are using multiple times that class in our program
Ex:
class Test{
p s v main(-){
Student s1=new Student();//here s1 is student object
//so when JVM come across this line JVM will load Student.class and creates class Class object.
Class c1=s1.getClass();//it returns class Class object.

Student s2=new Student();//here s2 is one more student object.
//now the JVM won't load .class file. because it got already loaded
Class c2=s2.getClass();;//here c1 and c2 are same both refer to same object.

System.out.println(c1.hashCode());//3222890
sop(c2.hashCode());//3222890
sop(c1==c2);//true

}
}

Linking:
Contains three activities
i.                     Verification 
ii.                   Preparation
iii.                  Resolution

i.                    Verification:
Java is a secured language. Through java spreading viruses and malware can’t be there. In old languages we may get alert saying this code may harm your system.
But in java it may not happen because in java we have Byte code Verifier.it is the responsible to verify the .class file.
It is the process of ensuring that binary representation of .class file structurally correct or not
Whether .class file properly formatted or not. Is whether it generated by valid compiler or not.
Internally bytecode verifier is the responsible for this process which is the part of Class Loader subsystem.
If verification fails then we will get Runtime Exception saying Verify Error.
ii.                  Preparation:
In this phase JVM will allocate memory for class level static variables and assigned with default values.
Note:  here just default values will be assigned and original values will be assigned in the initialization phase.
iii.                Resolution:
It is the process of replacing all symbolic references used in our class with original  references from method area.
Ex:
Class Test{
P s v main(-){
String s=new String(“durga”);
Student s1=new Student();
}
}
For the above class  Test  class loader sub system loads Test.class, Object.class, String.class, Student.class. The names of these class  stored in constant pool of the Test class.
In resolution phase these names are replaced with actual references from method area.
Nothing but programmer friendly symbols directly replaced with machine friendly references.


3. Initialization:
For static variables original values will be assigned and static blocks will execute from top to bottom.
Loading of a java class:


The above three activities can perform one by one or parallel that totally depends on JVM internal  implementation.
Most JVM’s follow one by one.
In these three phases if JVM phase any problem JVM will going to raise java.lang.LinkageError.
VerifyError is the child class of LinkageError.

1.    5.    Types of Class Loaders present inside Class Loader subsystem?

           Every class Loader subsystem contains 3 types of class loaders
i.                     Bootstrap Class loader\premodial class Loader
it is the responsible to load classes from Boot strap class path.
JDK\JRE\LIB\rt.jar[it is the boot strap class path]
Internally JVM will use rt.jar in order to load core java API’s
All core java API classes are by default available in rt.jar.
By default every JVM has Bootstrap Class Loader
And boot strap loader implemented in Native languages like c\c++.
ii.                  Extension Class Loader:
It is the child of Boot strap Class Loader. It is responsible to load classes from extension class path.
Extension class path: JDK\JRE\LIB\EXT\*.jar
It is implemented in Java language itself.
It is a java object. And its class name is
Sun.misc.Launcher$ExtClassLoader[$ means ExtClassLoader is the inner class]

iii.                Application class Loader\System Class Loader:
It is the child class of Extension class loader.
It is the responsible to load classes from Application class Path.
Like : classpath set in environment variables or default folder.
Application class loader implemented in java. And the corresponding class name is
Sun.misc.Launcher$AppClassLoader.class
Ex:
Class Test{
P s v main(-){
Sop(String.class.getClassLoader());//here Extension class loader is not a  java object so here we may get null
Sop(Student.class.getClassLoader());//place it in lib\ext by creating one Student class and create one jar file with that class.
Sop(Test.class.getClassLoaer());//current working directory
}
}
o/p:
null
sun.misc.Launcher$ExtClassLoader8989df
sun.misc.Launcher$AppClassLoader908de
what is the use of extclass folder?
2.       6. How Class Loader Works?

Class Loader subsystem follows delegation hierarchy algorithm to load a java class.
Ex: whenever JVM come across a particular class first it check whether it already loaded or not. If loaded in method area then JVM will use already loaded .class file in method area.
If it is not there then JVM requests Class Loader subsystem to load the particular .class.
Class Loader subsystem sends the request to application class loader. Then application class Loader delegates the request to Extension Class Loader. Then extension class loader to Bootstrap class Loader.
Now the bootstrap class loader search for .class files in Bootstrap class path.
If it is available then JVM loads the particular to .class file. If it is not there then Bootstrap CL delegates request to Extension CL. Then Extension CL search for the .class file in Extension CL path.
If it is there it will be loaded and if it is not there extension CL delegates the reques to Application CL. Application CL searches .class file in the application class path. If it is there it will be loaded. Other wise it will raise ClassNotFoundException.
Fig:
Highest priprity for the Bootstrap CL next Extension and then only Application CL.
Ex:
String.class[bootstrap classpath]
Student.class file present in [jre\lib\ext and application class path]in this case extension class loader is responsible to load Student.class file. Hence extension class path priority is more than application class path.


3.       7. JVM Architecture?


·         Initially we have java source file .java file. Java compiler is the responsible to generate .class file nothing but byte code.

·         So when ever we are executing JVM is the responsible to execue .class file.
·         In JVM class loader sub subsystem is responsible to load the .class file
·         Class Loader subsystem performs three activities loading,linking, initialization
·         In loading we have 3 types of class loaders Bootstrap Class Loader(loads from Bootstrap class path \jre\lib\rt.jar[all core java APIs]), Extension Class Loader[loads classes from  jre\lib\ext\*.jar], application Class Loader[loads classes from application level classes[environmental class paht]].
·         The highest priority goes to Boot strap Class Loader if it fails to load the particular class delegates the request to the next level Extension Class Loader if that also fails to load the .class then it delegates the request to application level class loader.
·         The algorithm that Class Loader subsystem follows for delegation is called Delegation Hierarchy algorithm
·         If application level class loader fails to load requested .class file then it raises exception saying ClassNotFoundException.
·         After loading immediately Linking will start
·         Linking will perform three activities Verification, Preparation, Resolution
·         Verification verifies the .class file is valid or not generated by valid compiler or not is it virus or something. If verification fails we get VerifyError. ByteCode verifier is responsible for this process
·         Preparation: all static variables are allocated memory and assigns with default values
·         Resolution:all symbolic references are replaces with original references from method area
·         Initialization: Static variables original values will be assigned and static blocks will be executed from top to bottom.
·         For .class for load and execution we need memory . so JVM contains 5 types of memory areas Method Area, Heap Area, Stack Area, PC Registers, Native Method Stacks.
·         Method Area : contains class Level Data including Static Variables
·         Heap Area: contains object data and corresponding instance variables
·         Stack Area:  for every thread a separate stack will be created. All local variables are stored inside stack only. Each stack entry is called Stack Frame. And each Stack Frame is divided into three parts Local Variable Array, stack Frame, operand Stack
·         Local Variables Array contains related to particular method total number of local variables are stored
·         Operand Stack: acts as a workspace for intermediate operations required to perform.
·         Frame Data: contains all symbols we have used in the method by default is going to take care. In the case of Exception if any exception occurs where the catch block information will be stored.
·         For every thread one Runtime Stack will be created.
·         Heap Area and Method area are shared by multiple threads. hence it is not thread safe.
·         For every thread on PC register will be created to hold the address of next executing instruction.
·         To hold Native methods information we have Native Method Stacks
·         W.r.t programmer Method area, heap area, Stack Area are important.
·         Execution Engine is the responsible to execute the .class file.
·         Execution eninge contains mainly two parts Interpreter and JIT compiler
·         JIT compiler contains intermediate code generator it produces intermediate code. Now the Code optimizer is responsible to optimize the code. And then Target Code generator is responsible to generate machine code or native code.
·         Interpreter: with interpreter we have one problem when we are using  same method multiple times every time we need to interpret. So instead of it we directly generate machined for that method only once. Next time onwards we can directly use the machine code without interpretation JIT compiler is the responsible for this process.
·         Sometimes while execution my execution may require Native Method Libraries. Hence java Native Interface is responsible to provide Native Method Information.
·         JVM arch FIG
Sometimes we may not satisfied with Default class loader. Then we may need to go for Customized Class Loader.
Ex:  usally in our application I may use my class multiple times. But that class will be loaded only once when ever we are using first time.so for the next time onwards it will load from method area.
Ex: default class loading mechanism

The problem here is after loading .class file suppose the file is modified  outside and the updated .class file won’t be loaded by default class loader.
After loading first time even though updated .class file is available second time default class loader won’t load updated file because it is already there in the method area.
Need of Customizer Class Loader:
When we are not satisfied with default class loader mechanism. We need to do.
What is the need of Customized Class Loader?

·         Sometimes we may not satisfy with  default Class Loader and default Class Loading mechanism
·         Ex: Default class loader loads .class file only once even though we are using multiple times that class in our program. After loading .class file if it is modified outside, then default class loader won’t load updated  version  of .class file on fly , because .class file already there in the method area.
·         Need of  Customized Class Loader?
ex: one scenario
Whenever we are using a class , customized class loader checks whether updated version is available or not if it is available then load updated version otherwise use already loaded existing .class file.  So that updated version available to our program.
The main advantage of customized class loader is we can customize class loading mechanism based on our requirement.
Defining our own customized Class Loader?
ClassLoader class present in java.lang package.
Public class CustomizedClassLoader extends ClassLoader{
@override
Public Class loadClass(String className)throws ClassNotFoundException
{
Check whether updated version available or not.
if updated version is available then load updated version and returns corresponding Class class object.
Otherwise return Class object of already loaded .class.
}
How to use the customized class loader:
Class CustomizedClassLoaderTest{
P s v main(-){
Student s1=new Student();
…..
CustomizedClassLoader c=new CustomizedClassLoader();
c.loadClass(“Student”);

….
c.loadClass(“Student”);
}
Where we can use Customized Class Loader?
While designing web servers &  application servers.
What is the purpose of ClassLoader Class?
We can use to define our own customized class loaders.
Every customized class loader in java extends ClassLoader class either directly or indirectly.
Acts as Base class for developing our own customized class loaders.
                                    





10. Program to display Heap memory statistics?
  i.maxmemory()
ii. totalmemory()
iii. freememory()


Comments

Popular posts from this blog

Database Definition and DBMS