You are on page 1of 34

JVM(Java Virtual Machine)

1. It is a part of JRE which is a part of JDK


BASIC FUNCTIONS OF JVM ARE:
• LOADING .class file
• RUNNING .class file

BASIC ARCHITECTURE OF JVM

CLASS LAODER SUBSYSTEM:


It is responsible for following 3 ACtivities
• Loading
• Linking
• Initialization
LOADING:
Loading means reading .class files and store corresponding binary
data in method area

For each class file JVM will store corresponding information in


the method area
• FQN(Fully Qualifies NAme)
• FQN of Immediate parent class
• Mehods info
• Variable info
• Constructors info
• Modifers info
Constants pool imformation...etc

After loading the .class file into the method area immediately
jvm creates an object for that loaded class in the heap
memory.......of TYPE (java.lang.class)
The object created is not of the type of .class file
Instead it is of type “CLASS”....here total 3 parts of memory are
involved ie 2parts of JVM and 1 part of our
Local hard disk.
WHY DOES JVM CREATE THE OBJECT OF THAT LOADED CLASS
IN HEAP AREA????
ANS: THE OBJECT of class “CLASS”representing the actual .class
file provides complete information of the .class to
programmers......ie HOW MANY METHODS ARE PRESENT
…,constructor info.....how many constants present...and so
on....!!
The class “CLASS” object can be used by programmer to get
class information.....

HOW TO USE THIS clas “CLASS” object


Eg:
Import java.lang.reflect;
Class student{
Public int getMarks(){
Return 10;
}
Public String getName(){
Return null;
}
}
Class test{
Public static void main(String[] args){
Int count=0;
Class c=Class.getName(“Student”);
Method[] m=c.getDeclaredMethods();
For(int I=0;I<m.length;I++){
Count++;
System.Out.pritnln(I.getName());
}
System.out.println(“the number of methods are:”+ count);
}
}
For every loaded type only one “CLASS” object will be created
even tough we are using the class multiple times in our
program.

Eg:
Class student same as above
Class test{

P s v main(Strings args[]){
Student s1=new studenr();
Class c1=s1.getClass();
Student s2=new student();
Class x2=s2.getClass(); System.out.println(c1.hashCode);
System.out.println(x2.hashCode);
System.out.println(c1==x2);

Output
123345454444
123345454444
TRUE

Here student .class gile was in system s hard disk


Which is loaded onto method area by a class loader
subsystem....anad claa Class object is created in heap AREA....as
a representation of that loaded class....even tough we use
multiple object of a class …..only one class Class object is
created

LINKING consists of 3 activities :


• Verify
• Prepare
• Resolve

VERFICATION:
It is the process of ensuring that binary representation of class
is structurally correct or not..! Ie JVM will check whether the
.class file is generated by valid complier or not ie whether .class
file is properly formatted or not.

INTERNALLY BYTE CODE VERIFIER is reponsible for this activity.


Byte code verifier is the part of CLASS loader subsystem
IF verification fails we get runtume exception
“Java.lang.verify”error

PREPARATION :
In this phase jvm will allocate memory for class level static
variables and assign default values.
In initialization phase the original values will be assigned to the
static variables.....but here only default values will be allocated

RESOLUTION:
It is the process of replacing symbolic names in our program
with original memory refrences from method area .
Eg:
Class test{
Public static void main (String args[]){
String s=new String(“DURGA”);
Student ss1 =new Student();
}
}

For the above class class loader loades test.class


String.class
Student.class
And object.clasS

The names of these classes are stored in Constant


Pool of test class.
In resolution phase these names are replaced with
original memory level refrences from method
area.

INITAILIZATION:

In this all stactic variables are assigned with


original values.
Static blocks are also executed in this phase.
From parent to child and from top to bottom
While loading ,linking and initalization if any error
occurs then we will get run time exception
saying”java.lang.linkageError”
“java.lang.verify error”is a subclass of linkage error

TYPES OF CLASS LOADERS

BOOTSTRAP CLASS LAODER/PRE MODIAL


• It is responsible to load rt.jar ie CORE JAVA
API CLASSES.....classes present in rt.jar.
• Path for BOOTSTRAP CLASS LOADER IS
Jdk/jre/lib/rt.jar. This loaction is called
BOOTSTRAP CLASS path.ie it Is responsible to
load classes from bootstarp class path

BOOTSTRAP CLASSLOADER is bydefault available


with every JVM.
IT is implemented in native languages like
c/c++….and not implemented in java.(since it
available by default with ebvery JVM)

EXTENSION CLASSLOADER:
Extension class loader is the child class of
bootstrap class loader .
It is responsible to load class from extension
class path.....ie
Jdk/jre/lib/ext/*.jar(any class present here is
loaded)
• Extension class loader is implemented in java
and corresponding .class file is
sun.misc.Launcher$ExtClassLoader.class
APPLICATION CLASS LAODER OR SYSTEM CLASS
LOADER:
• IT is the child class of Extension class loader.
• This class loader is responsible to load classes
from application class path’
• It internally uses environmental class path.
• Application class loader is Implemented in java
and corresponding .class name is
Sun.misc.Launcher$AppClassLoader.class
HOW CLASS LOADER WORKS??

THIS IS ALGORITHM OF CLASS LAODER


• First jvm checks whether .class file is loaded or
not if it is loaded in method area then jvm will
consider that loaded class
• If it is not loaded then jvm class loader
subsystem that particular class...
• The rest is explained in diagram
• Finally priority wise:
• Highest priority is given to BOOTSTRAP -
>EXTENSION->APPLICATION
Eg:
Class test{
Psvmain(String arg[]){
Sop(String.class.getClassLoader());
Sop(Test.class.getClassLoader());
Sop(Customer.class. getClassLoader());
/*(here if customer class is present in both
current directory ie ((application class path) and
ext then according to priority based )*/
}
}

To create a jar file


Jar –cvf cust.jar Customer.class

For string class as shown above


The class loader responsible to load it is
BOOTSTRAP but since it is not a java object we
get the output as null.
For testclass the output will be
Sun.misc.LAuncher$AppClassLoader@122345

This algorithm is called delegation hierarachy algorithm.

NEED OF CUSTOMIZED CLASS LOADER


Default class loaders will load .class file only once
Even though we use the class file multiple times in our program
After loading .class file if it is modified outside then default class
loader wont load updated version version of class file....beacuse
.class file already available in method area
We can resolve this problem by defining our own customized
class loader
The main Advantage of cuatomized class lodaer is we can
control class loading mechanism based on our requirement....for
example we can load .class file
Separately everytime so that updated version available to our
program
HOw to define Customised class loader??
We can define our own customised class loader by extending
java.lang.classLoaderClass
Eg;

public class CustomisedCLAssLaoder extends ClassLoader {

@Override
public Class<?> loadClass(String name) throws
ClassNotFoundException {
//check for updates and return coreesponding class object
//if specified .class file is not available throw class not found
exception

return super.loadClass(name);
}

public class Client {


public static void main(String[] args) throws
ClassNotFoundException {
Dog d1=new Dog();// here deafult laoding occurs

//check for an update an then load ....so this is customised


loading
CustomisedCLAssLaoder c=new CustomisedCLAssLaoder();
c.loadClass("Dog");//loaded by customised class loader

//while designing orn developing web servers and application


servers usually we use customized class loaders to customise
class loading mechanism
}
}
INTERVIEW QUESTION
Need or use of classLoader class?
We can use java.lang.ClassLoader class to define our own
customised class loaders.
Every class loader in java should be child class of
java.lang.ClassLoader class either directly or indirectly hence
this class acts as base class for all customised classLoaders.

VARIOUS MEMORY AREAS PRESENT INSIDE JVM!


Whenevr JVM loads and runs a java program it needs
meemory to store various things such as
bytecode,variables,objects...etc

Total JVM memory organised into following 5 categories


1. Method area
2. Heap area
3. Stack memory
4. Pc registers
5. Native method stacks
Method AREA:
For every JVM there is ONe method area which is always
available
method area will be created at the time JVm startup
• Inside method area class level binary data including static
variables will be stored
• Constant pools of a class will be stored inside method area
• Method area can be accesed by multiple threads
simultaneously.

HEAP AREA:
• For every JVM one heap area is available
• Heap area will be created at the time of JVM startup
• Objects and correponding instance variables will be stored in
the heap area
• Every array in java is object only hence arrays will also be
stored in heap area
• Heap area can be accesed by multiple threads hence data
stord in the heap memory is not thread safe.
• HEAP area need not be continuous.

PROGRAM TO DISPLAY HEAP MEMORY STATISTICS

A java application can communicate with JVM by using runtime


Object

Runtime Class present in java.lang package and it is a single ton


class we can create runtime object as follows

Runtime r=Runtime.getRuntime();
Once we get runtime object we can call the following methods
on that object
1. maxMemory();(returns number of bytes of max memory
allocated to the heap)
2. totalMemory(); it returns number of bytes of total memory
allocated to the heap (initial memory)
3. freeMemory();it returns number of bytes of free memoory
present in the heap.
Eg:

public class HeapDemo {

public static void main(String[] args) {


Runtime r= Runtime.getRuntime();
System.out.println("max memory
"+r.maxMemory()/(1024*1024)+" mb");
System.out.println("initial memory
"+r.totalMemory()/(1024*1024)+" mb");
System.out.println("free memory
"+r.freeMemory()/(1024*1024)+" mb");
System.out.println("consumed memory
"+(r.totalMemory()-r.freeMemory())/(1024*1024)+" mb");
}// to convert bytes to mb

}
Output:
max memory 1801 mb
initial memory 123 mb
free memory 121 mb
consumed memory 1 mb

Is it possible to set maximum and minimum


heap size??
Yes it is possible.........!!!

HEAP memory is finite memory but based on our requirement


we can set maximun and minimium heap sizes ie we can
increase or decrease heap size based on our require ment.....
We can use the following flags with java command
1.to set maximum heap size ie(maxMemory())
We use...”java -Xmx512m Heapdemo”(heapdemo is name of
the class) this command will set heap size as 512 mb.
2.”java -Xms64m Heapdemo” this command is use to set
minimum heap size as 64 mb

STACK MEMORY:
For every thread JVm will create a separate stack at the time of
thread Creation
Each and every method call performed by that thread will be
stored in the stack including local variables...
After completing a method the corresponding entry from the
stack will be removed after completing all method calls the
stack will become empty …..and just before the termination of
thread
That empty stack will be destroyed by the JVM.
Each entry in the stack is called STACK FRAME

♦ The data stored in the stack is available only to that


corresponding thread and not available to the remaining
threads.
♦ Hence this data is thread safe

Stack FRame STRUCTURE


• Each stack frame contains 3 parts
1. Local VAriable array
2. Operand array
3. Frame data
LOCAL VARIABLE ARRAY:
It contains all parameters and local variables of the method .
Each slot in the array is of “4 bytes”
Values of type int,float and reference variable occupy one entry
in the array.
Values of type char,short and byte are converted to 4 bytes
before storing it in the array and then takes one slot.
Values of type long,double take 2 consecutive slots in the array.
Value of type boolean is unpredictable as it depends on the
JVM and varies from jvm to jvm.

OPERAND STACK:
JVM uses operand stack as workspace some instructions can
push the values to the operand stack
And some instructions can perform required operations
Basic idea of operand stack.....
instructions as mentioned earlier such as iload-0,iload-1,iadd,I
store these are assembly imstructions we don’t have to worry
about........

FRAME DATA:

IT contains all symbolic references related to that method it


also contains a reference to exception table....which provides
corresponding catch block information in case of exceptions

PC REGISTERS:(PROGRAM COUNTER REGISTERS)


For every thread a separate pc register will be created at the
time of thread creation
Pc registers contains the adress of the current executing
instruction
Once instruction execution completes automatically pc register
will be incremented to hold address of next instructions

NATIVE METHOD STACKS:


For every thread jvm will create a separate native method stack
All native method calls invoked by the thread in the
corresponding native method stack

CONCLUSIONS:
Method area ,Heap area, STACK area are considered as
important memory areas with respect to programmer
Method area and heap area are per jvm
Stack area ,pc registers ,native method stack …..are per thread.
Static variables are stored in Method area.
Instance variables in Heap area
Local variables in Stack area.

Class test{
Student s1=new Student();
Static Student s2=new Student();
P s v main(String args[]){
Test t=new Test();
Student s3=new Student();
}
}

JAVA EXECUTION ENGINE:

This is the central copmonent of JVM.


Execution engine is responsible to execute java class files.
Execution engine two components
• Interpretor
• Jit compiler

INTREPRETOR:
It is responsible to read byte code and intrepret into machine
code (native code) and execute that machine code line by line.
The problem with interpretor is it interprets everytime
Even same method invoked multiple times......which reduces
performance of the system.
To overcome this problem sun people introduced JIT compiler in
1.1 version.

JITM COMPILER:
The main purpose of jit compiler is to improve performance
internally …....jit compiler maintains a separate count for every
method
Whenever JVM come across any method call the methods gets
interpreted normally …..by the interpretor and jit compiler
increments...the corresponding count variable...if the count
reaches then threshold count...
Then jit compiler indentifies that the method is a repeatedly used
method ….such methods are called “HOT SPOTS”immediately jit
compiler compiles that method and generates the corresponding
native code...
Next time if the JVM comes across that method call then the JVM
uses the native code directly and executes it.....instead of again
interpreting it once again..so that performance of system is
improved....

Threshold count varies from JVM TO JVM.

Some advanced jit compiler recompile the generated Native


code.......if count reaches threshhold value second time....so that
more optimised machine code will be generated...

Internally profiler,which is the part of jit compiler is responsible to


identify hot spots .

NOTE:
JVM INTERPRETS the total program atleast once …..
JIT compilation is applicable only for repeatedly required
methods not for every method...

VARIOUS PARTS IN EXECUTION ENGINE:


JAVA NATIVE INTERFACE:(JNI):
it acts as mediator for java method calls and corresponding native
libraries....ie JNI to provide information about native libraries to
JVM.
Native method libraries provides or holds native libraries
information....

COMPLETE JVM ARCHITECTURE


CLASS FILE STRUCTURE:

public class File {


//for every .class file jVm generates cerates and saves ceratin
information
//they are stored in method area

magic_number;
minor_version;
major_version;
constant_pool_count;
constant_pool[];
access_flags;
this_class;
super_class;
interface_count;
interface[];
fields_count;
fields[];
methods_count;
methods[];
attributes_count;
attributes[];
}

magic_number;:
the first 4 bytes in every .class file should be....0XCAFEBABE
So that the JVM VERIFIES WHETHER .class FILE IS GENERATED BY
A VALID COMPILER.
This value is predefined …...

When ever we are executing a java class if the JVM is not able to
find valid magic number we get runtime exception saying.
Java.lang.ClassformatError:Incompatible magic value
Major and minor version represent .class file version
Jvm will use these versions to identify which version of compiler
the current .class file

M.m(M->major m->minor)
1.5v-m->value 49.0
LOwer version copmiler generated .class files can be run by
higher version JVM.

But vice versa we get an exception:


“unsupported class version error”

Constant pool count:


it represents number of constants present in constant pool
Constant_pool[](array):
It represents information about constants present in constant
pool.
Access_flags:
It provides information about modifiers which declared in the
class.
This_class:
It represents fully qualified name of the class....
Super_class:
It represents fully qualified name of immediate super class... of
current class.
Interface_count:
It returns number of interfaces implemented by current class
Interface array[]:
It returns interfaces information implemented by current class.

Fields_count:
Number of fields present in current class.
Here fields are Static variable,static bloacks////etc
Methods_count:
It represents number of methods present in current class.
Methods_array:provides information about all methods present
in current class
Attributes_count:
It returns/represents number of attributes present in current
class.
Attributes_count:
It provides information attributes present in current class.
Attributes are instance variables.

You might also like