Showing posts with label JVM. Show all posts
Showing posts with label JVM. Show all posts

Dec 10, 2019

Understanding JVM: JVM Execution Engine

Now we know that how classes are loaded by Class Loaders, which are part of Class Loader Sub System, next thing that happens is the execution of those class files. JVM Execution Engine is the responsible component for this. It has two components:
  • Interpreter
  • JIT Compiler

Interpreter

  • It reads the byte code, interpret it into machine code (native code) and then execute them line by line.
  • Problem with interpreter is it interprets every-time even if same method invoked every-time which reduces performance of the system.
  • To overcome this problem, "Sun" introduced JIT Compiler in 1.1 version.

JIT Compiler

  • Main purpose of JIT Compiler is to improve performance. Internally it maintains a separate count for every method.
  • Whenever JVM comes across any method call, first that method will be interpreted normally by interpreter and JIT Compiler increments corresponding count variable.
  • This process is done for every method being executed.
  • Once any method reaches a threshold value, JIT Compiler identifies that this method is commonly used method. These commonly used methods are also called hot-spot.
  • Immediately JIT Compiler compiles that method and generates corresponding native code. Next time, for this method call, generated native code is used directly instead of interpreting it once again.
  • Threshold count varies from JVM to JVM.
  • Some advanced JIT Compilers recompile generated native code, if count reaches threshold value second time, so that more optimized machine code is generated.
  • Internally, profiler, which is part of JIT Compiler is responsible to identify hot-spots.
  • One thing to note here is that JVM interprets whole program at least once. JIT compilation is done only for repeatedly used methods, not every method.

With that, we are done with the series for JVM understanding. Please let me know your view and if you want any other topic to be covered.

Nov 15, 2017

Understanding JVM: Memory Areas in JVM - Part 3

We have already covered Method Area, Heap Area and Stack memory in previous articles. This article will give brief overview of the remaining 2 memory areas in JVM, i.e., PC Registers and Native Method Stack.

PC Register (Program Counter Registers)

  • It is internally used by JVM and like Stack Memory, every thread keeps a separate PC register, which is created at the time of thread creation.
  • It contains the address of currently executing instruction.
  • Once instruction execution completes, automatically PC register is incremented to hold the address of next instruction.

Native Method Stack

  • JVM creates a separate Native Method Stack per thread.
  • Again, it is internally used by JVM. All native calls invoked by thread will be stored in corresponding native method stack.

This concludes the topic of Memory Areas inside JVM. To summarize things:
  1. Method area, heap area and stack area are considered most important with respect to programmers.
  2. Method and heap area are per JVM.
  3. Stack memory, PC registers and Native Method stack are maintained per thread.
  4. Static variables are stored in Memory Area
  5. Instance variables are stored in Heap Area
  6. Local variables are stored in Stack Area

Let us write a simple program to understand things better: 

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package edu.javaterritory.example.methodarea;

public class Test {

 private Student s1 = new Student();
 private static Student s2 = new Student();
 
 public static void main(String[] args) {
  Test t1 = new Test();
  Student s3 = new Student();
 }
}

Following diagram shows where variables created in above program will be stored.

  • Static variables inside method area
  • Instance variables in heap area
  • Local variables in static memory area

So, that's all about method area's inside JVM. Hopefully it helps.
We will continue to remaining components inside JVM, i.e., Execution Engine and JNI (Java Native Interface).

Please provide your inputs in the comments section.
Also, you can follow us at +Java Territory (or here).

Nov 5, 2017

Understanding JVM: Memory Areas in JVM - Part 2

Stack memory

  • It is maintained per thread, i.e., for every thread in Java, JVM will create a separate stack at the time of thread creation.
  • Each and every method call performed by the thread will be stored in stack including local variable also.
  • After completing a method, the corresponding entry from the stack will also be removed. Thus, once all method calls are completed, stack memory will become empty.
  • This empty stack will be destroyed by JVM before terminating the thread.
  • Data stored inside stack is private to corresponding thread only and hence thread-safe.
  • Each entry inside stack is called stack frame/activation record.

Stack Frame structure

Each Stack Frame has 3 parts:
  1. Local Variable Array,
  2. Operand Stack, and
  3. Frame Data
    Local Variable Array
    • It contains all parameters and local variables of the memory.
    • Each slot in the array is of 4 bytes.
    • Type
      • int, float, object -> 1 slot (4 bytes)
      • double, long -> 2 slots (8 bytes)
      • byte, short, char -> converted to int before storing -> 1 slot (4 bytes)
      • boolean -> JVM dependent -> generally 1 slot
    Operand Stack
    • It stores intermediate values.
    • JVM uses operand stack as workspace.
    • Some instructions can push values to operand stack, some instructions can pop values, and some can performance required operations.
    Lets take an example to understand the process. Suppose a program adds 2 values, say 40 and 60.
    JVM instructions will look something like:
    iload - 0 // loads 40
    iload - 1 // loads 60
    iadd // adds 40 and 60
    istore -2 // store the result

    Following is the state if Local Variable Array after first 2 load instructions.
    Local Variable Array

    Values are also loaded in Operand Stack for addition. 
    Operand Stack


    Finally, sum is  pop out from the operand stack and put into local variable array.
    Local Variable Array

    Finally the third component in the frame is Frame Data.

    Frame Data

    • It contains all symbolic references related to the method.
    • Contains references to exception table and will provide corresponding catch block information in case of exception.
    This is all about Stack Memory. Hopefully, it helps.
    Next section will cover the other 2 memory areas, PC registers and native method stack.

    If you like reading our articles, do follow at +Java Territory / Java Territory.

    Oct 11, 2017

    Understanding JVM: Memory Areas in JVM - Part 1

    Whenever JVM load and run a Java program, it needs memory to store several things like bytecode, objects, variables, etc. Total JVM memory is organized into following:

    • Method Area
    • Heap Area
    • Stack Area
    • PC Registers
    • Native Method Stack

    1. Method Area

    • It is created at the time of JVM startup.
    • .class file's binary information is stored into method area.
    • Static variables are stored in method area.
    • Data inside method area is not thread safe.
    • Method area is not contiguous memory.
    • For every JVM, one method area is available.
    • Constant pools of a class are store inside method.

    2. Heap Area

    • There is one heap area per JVM.
    • Like method area, it is also created at the time of JVM startup.
    • Need not be contiguous memory.
    • Objects and corresponding instance variables are 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 accessed by multiple threads, and hence data in heap area is not thread safe.
    Program to Display heap memory statistics
    Heap memory statistics can be captured using Runtime instance. Runtime class is present in java.lang package. It is a singleton class.
    Following code snippet demonstrate how Runtime object can be obtained and used to get heap statistics:

    package com.javaterritory;
    
    public class MemoryTest {
    
     public static void main(String[] args) {
      Runtime r = Runtime.getRuntime(); // get instance of Runtime
      System.out.println("Max memory: " + r.maxMemory()); // prints memory (number of bytes) allocaed to JVM
      System.out.println("Total memory: " + r.totalMemory()); // prints initial memory (in bytes) allocated to JVM
      System.out.println("Free memory: " + r.freeMemory()); // prints the free memory 
     }
    }
    

    Following were the results when I executed it on my machine:

    Max memory: 3797417984
    Total memory: 257425408
    Free memory: 254741016
    

    How to set maximum and minimum heap size
    Following JVM arguments can be used to configuring heap size;
    -Xmx 512m : to set maximum heap size to 512 mb
    -Xms 64m : to set initial heap size to 64 mb

    This is it for Method and Heap area. Next section will cover the stack memory area.
    If you like reading our article, connect with us at +Java Territory  / Java territory to stay updated.

    Oct 7, 2017

    Understanding JVM: How Class Loader works?

    Previous article was related to the types of class loader. I this post, we will see how these types works to load a class file. 

    Class loader sub system follows Delegation Hierarchy algorithm for loading any class file. It is explained below.

    Step 1: When request comes for a class file, JVM first look if is already loaded or not.
    Step 2: If already loaded, JVM finds it in the memory area.
    Step 3: If not, it requests class loader sub system to load the requested class file.
    Step 4: Class loader sub system first sends the request to Application class loader.
    Step 5: Application class loader delegates the request to Extension class loader.
    Step 6: Extension class loader delegates it further to Bootstrap class loader.
    Step 7: Bootstrap class loader searches class file in the bootstrap class path. If found, it is loaded.
    Step 8: If not found, Bootstrap class loader delegates request to Extension class loader.
    Step 9: Extension class loader searches it in the extension class path. If found, it gets loaded.
    Step 10: If not found, request is again delegated to the  Application class loader which searches class file in the application class path and loads if found.
    Step 11: If still not found, ClassNotFoundExcetpion is thrown.

    Thus, Bootstrap class loader has the highest priority while Application class loader has the lowest. If same name class file is present in more than one class paths, higher priority class loader will be given the preference.

    In next article, we will talk about how can create a custom class loader and what is the need for it.
    If you like reading our articles, do like and share with other peoples. You can also connect with us at +Java Territory or Java Territory to stay updated.

    Sep 27, 2017

    Understanding JVM: Types of Class Loaders

    Every class loader sub system contains 3 types of class loaders:
    1. Bootstrap/Primordial class loader
    2. Extension class loader
    3. Application class loader

    Bootstrap class loader

    It is responsible to load from bootstrap class path, where core java classes are available.
    Bootstrap class path
    String, StringBuffer, are the examples of classes that are loaded by bootstrap class loader.
    Bootstrap class loader

    • comes with every JVM
    • implemented in native language not JAVA

    Extension class loader

    It is child of bootstrap class loader and responsible for loading classes from extension class path.
    Extension class path
    Extension class loader:
    • is implemented in JAVA language
    • can be found at sun.misc.Launcher$ExtClassLoader.class ($ means ExtClassLoader is an inner class of Launcher)

    Application class loader

    • loads class files from application class path (examples: Student.class, Address.class)
    • child of Extension class loader
    • implemented in JAVA
    • located at sun.misc.Laucher$AppClassLoader.class ($ means AppClassLoader is inner class in Launcher)
    Next article, How Class Loader Works, will explain in detail how these class loaders work together and in what order to load class files.
    Join us at +Java Territory or facebook to stay updated with articles.

    Aug 5, 2017

    Understanding JVM: Class Loader Sub System - Part 2

    First part of class loader sub system talked about the Loading of class files. Next task that is performed by the class loader sub system is Linking.

    Linking 

    It performs 3 activities:
    • Verification
    • Preparation
    • Resolution

    Verification

    • It is the process of ensuring binary representation of class file (output of Loading) is correct or not. Correct means if .class file is properly formatted or not, and it is generated by valid compiler or not.
    • Internally Byte Code Verifier, which is part of Class Loader Sub System, is responsible for this activity.
    • If verification fails, then it will throw the run-time exception, java.lang.VerifyError.

    Preparation

    • In preparation phase, JVM will allocate memory and assign default values for class level static variables. For example:
      • For int --> 0
      • For double --> 0.0
      • For boolean -->false
      • For object --> NULL
    • It is important to note here that only default values are assigned in this phase, actual values (as defined in the class will be assigned in initialization phase. That means if a class variable is declared as,  private static int count = 10, 0 will be assigned in the preparation phase.

    Resolution

    • All symbolic references are replaced with original direct references from method area. (Method area will be explained in coming articles). For example, consider following code:
     class Test {  
          public static void main(String[] args) {  
               String name = new String("Java Territory");  
               Student s1 = new Student();  
          }  
     }
    
    • In the above example, class loader sub system loads 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 actual references from the method area of JVM.
    After Linking is done, Initialization of class files are done.

    Intialization
    • After Loading and Linking of class files are done, JVM will assign original values (as declared in the class file) to the class level static variables.
    • Also, static blocks are executed during this phase.
    Following diagram explains the functions performed by Class Loader Sub System:
    If any error comes Loading, Linking or Initialization, JVM will raise runtime exception, java.lang.LinkageError.

    VerifyError is a child class of LinkageError.

    This is all for Class Loader Sub System. In next article, I will talk about the Types of Class Loaders. Please post your inputs in the comments section and if you like reading our article, follow us @ +Java Territory / facebook to stay connected and get notifications for new articles.

    Jul 10, 2017

    Understanding JVM: Class Loader Sub System - Part 1

    Now we know from the previous article that JVM is responsible for loading od the Java class file. Internally Class Loader Sub System performs following steps:
    1. Loading
    2. Linking
    3. Initialization
    Loading: Loading means reading .class file data and store corresponding data in method area. For each .class file, JVM will store following information:
    • fully qualified name of class
    • fully qualified name of immediate parent
    • whether .class file represents class/interface/enum
    • methods/constructors/variables information
    • modifiers information
    • constant pool information
    After .class object is loaded into memory, JVM then creates the "Class" object for the the same. This object can be used to retrieve class level information like how many methods are there in class, using reflection. 

    It is important to note that for every class, only one "Class" object will be created by JVM. Consider following example:

    1:  public class Exmaple {  
    2:       Student s1 = new Student ();  
    3:       Class c1 = s1.getClass();  
    4:       Student s2 = new Student ();  
    5:       Class c2 = s2.getClass();  
    6:  }  
    

    In the above example, s1.getClass() and s2.getClass() will give same object as there is only one object of Class class of Student.

    Classloader subsystem first loads class file and stores in method area. Then JVM creates object of Class class.

    Next section will be on the second activity performed by Class Loader Sub System, i.e., Linking.
    Join us at +Java Territory or facebook to stay updated.

    Understanding JVM: Introduction

    What are Virtual Machines?

    Virtual machine is something which does not have a physical existence, for example, PC calculator. In other words, it is a software simulator of a machine that can perform operation like a physical machine, hence the name - Virtual Machine.

    Types of Virtual Machines

    There are 2 types of virtual machines:
    1. Hardware based / System based:  These are multiple logical VM, independent of each other, working a single physical VM, example of the same are Kernal Based VM (for Linux), VMware, Cloud Computing, etc. Hardware based VMs results in effective utilization of resources. However it is more related to admin terminology, not programmer.
    2. Application based / Process based / Software based:  These VMs acts as run-time engine to execute a particular programming language application. Example: 
        • JVM - For Java
        • CLR - For .net
        • PVM - For Parrot (scripting language)

    Basic architecture Diagram of JVM

    JVM is the run time engine to execute Java applications and is part of JRE. It loads and executes application line by lines.

    Following is the basic architecture diagram:
    Different components in the above diagram will be explained in the coming tutorials. Go to Class Loader Sub System to read first component.