Monday, April 13, 2015

Java Class Loader Sub-system

 The class loader performs three main functions of JVM : loading, linking and initialization.

  • Loading - Loading means reading the class file for a type, parsing it to get its information, and storing the information in the method area. Class loader sub-system follows delegation hierarchy algorithm for this. Whenever JVM come across a particular class, first it will check whether the corresponding class is already loaded or not. if it is loaded in the method area then JVM will use that loaded class else JVM requests class loader subsystem to load that particular class, then class loader subsystem handover the request to application/system class loader. System class loader delegates request to extension class loader and extension class loader in turn delegates to boot strap class loader. Bootstrap class loader searches class in bootstrap class path (/jre/lib). If the specified class is available then it will be loaded otherwise bootstrap class loader delegated the loading request to extension class loader. Extension class loader will search in extension class path (/jre/lib/ext) or any other directory specified by the java.ext.dirs system property. If the specified class is available then it will be loaded otherwise request will be delegated to application/system class loader. Application class loader will search in application class path. If the specified class is available then it will be loaded(creation of an instance of java.lang.Class for the loaded type) else JVM will throw runtime exception : classNotFoundException


Note: The bootstrap class loader loads the core Java libraries located in the /jre/lib directory. These libraries are stored in Jar files called rt.jarcore.jarserver.jar, etc. This class loader, which is part of the core JVM, is written in native code. The system class loader loads code found on java.class.path, which maps to the CLASSPATH environment variable.



  • Linking: The next process handled by the class loader is Linking.  This involves three sub-processes: Verification, Preparation and Resolution


o   Verification - Verification is the process of ensuring that binary representation of a class (bytecode) is structurally correct. The JVM has to make sure that a file it is asked to load was generated by a valid compiler and it is well formed.
Some of the things that are checked at verification are:
§  Every method is provided with a structurally correct signature 
§  Every instruction obeys the type discipline of the Java language
§  Every branch instruction branches to the start not middle of another instruction

Java compiler ensures that Java source code doesn't violate the safety rules but, when an application imports a code fragment, it doesn't actually know if the code fragment follows Java language rules for safety. In other words, the code may not have been produced by a trustworthy Java compiler. In that case, the Java run time system on your machine has to assume the fragment is bad and subjects it to bytecode verification.
The Java virtual machine does not even see the bytecode until it's been through this verification process. Doing this as the bytecode is loaded also has the advantage that a whole lot of run time checks don't need to be performed every time the code is executed. Because it's been verified as correct, it can, once it starts running, run faster than would otherwise be possible.

o   Preparation - In this phase, the JVM allocates memory for the class (i.e. static) variables and sets them to default initial values. Note that class variables are not initialized to their proper initial values until the initialization phase - no java code is executed until initialization. The default values for the various types are as follows :  byte(0), short(0), int(0), long(0L), float(0.0f), double(0.0d), Boolean(false)

o   Resolution - Resolution is the process of replacing symbolic names for types, fields and methods used by a loaded type with their actual references. Symbolic references are resolved into a direct reference by searching through the method area to locate the referenced entity.

  • Initialization: it is a process of setting class variables to their proper initial values - initial values desired by the programmer. Initialization of a class consists of two steps:   

o   Initializing its direct superclass (if any and if not already initialized)
o   Executing its own initialization statements
It means that, the first class that gets initialized is Object (which is superclass of all the classes). However, static final variables are not treated as class variables but as constants hence their values are assigned at compilation.

Once class is loaded, linked, and initialized, it is ready for use. Its static fields and static methods can be used and it can be instantiated. When a new class instance is created, memory is allocated for all its instance variables in the heap. Memory is also allocated recursively for all the instance variables declared in its superclass and all classes up is inheritance hierarchy. All instance variables in the new object and those of its superclasses are then initialized to their default values. The constructor invoked in the instantiation is then processed. Finally, the reference to the newly created object is returned as the result.


Related Topics :

Friday, April 10, 2015

JVM Runtime Data Areas


The JVM runtime data areas are used in program execution. Some are created on JVM start-up and destroyed when JVM exits, while others are per thread which created when thread is created and destroyed when thread exits. Following are the various runtime data areas :
1.   Method Area: Method area is created on JVM start-up and shared between all the JVM threads. Complied java file or .class file is dumped in to method area. Method area stores class structure in following parts:

  •          Type Information – fully qualified type’s name, super class name, type’s modifiers, whether class or interface
  •          Run-time constant pool – an ordered set of constants like string, integer, final variables etc. It also stores symbolic references to types, methods and fields
  •          Field Information – field name, type and modifiers. A Java field is a variable inside a class.
  •          Method Information – Method’s name, return type, modifiers. The number and types (in order) of the method's parameters.
  •          Class variables – ordered set of class variables (static variables).
  •          Reference to Class loader and class Class - reference to class loader is used for dynamic linking.  instance java.lang.Class is created every type for the following info.
o   getName();
o   getSuperClass();
o   isInterface();                                     
o   getInterfaces();
o   getClassLoader();
·         Method table - For each non-abstract class a Java virtual machine loads, it could generate a method table and include it as part of the class information it stores in the method area. A method table is an array of direct references to all the instance methods that may be invoked on a class instance, including instance methods inherited from superclasses.

2.   Heap Area: Objects and arrays are allocated in this area. There is only one heap inside a Java virtual machine instance and all threads share it. The heap is created on virtual machine start-up. The heap size can be changed using commands :
-Xms - Set initial Java heap size
-Xmx - Set maximum Java heap size

Insufficient Heap size will cause java.lang.OutOfMemoryError: Java heap space. To free memory from heap java uses garbage collector.

3.   Stack Area: Java virtual machine creates a new Java stack for each thread. Each and every method called by thread will be stored in corresponding Stack including local variables. When a thread invokes a Java method, the virtual machine creates and pushes a new frame onto the thread's Java stack. Each entry in stack called stack frame which contains local variable array, Operand stack, frame data and reference to runtime constant pool for class of the current method. All the data on a thread's Java stack is private to that thread. There is no way for a thread to access or alter the Java stack of another thread. Because of this, local variables are thread safe in multi threading environment.

Stack Frame - used to store data and partial results, as well as to perform dynamic linking, return values for methods, and dispatch exceptions. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes (Normal or abrupt/exception). Stack frame has three parts: local variables, operand stack, and frame data
·         Local Variables –
o   The sizes of the local variables are measured in words and determined at compile time, which further added in the class file data for each method.
o   The local variables section of the Java stack frame is organized as a zero-based array of words.
o   Values of type long and double occupy two consecutive cells in the array, rest takes one cell.

·         Operand Stack –
o   This area is used by all the opcode instructions (portion of a machine language instruction that specifies the operation to be performed).
o   Size of the operand stack is measured in words and determined at compile time, which further added in the class file data for each method.
o   Like the local variables, the operand stack is organized as an array of words but accessed by push and pop values.
o   JVM uses the operand stack as a work space. Many instructions pop values from the operand stack, operate on them, and push the result.

·         Frame Data –
o   Includes data to support constant pool resolution, normal method return, and exception dispatch.
o   JVM uses the frame data's pointer to the constant pool to access the information when it encounters an instruction that refer to an entry in the constant pool
o   Frame data also help JVM in processing a normal or abrupt (exception) method completion. In case of normal method completion JVM restore the stack frame of the invoking method, where as in case of exception JVM uses the exception table referred to by the frame data to determine how to handle the exception.



4.   PC Register - Holds address of current executing instruction. If the current executing method is ‘native’, then the value of program counter register will be undefined. The pc register is one word in size, so it can hold both a native pointer and a returnAddress. For every thread a separate PC registers will be created.

5.   Native method Stacks – Native method stacks are typically allocated per thread when each thread is created. Native methods (methods written in a language other than the Java programming language) are implementation dependent. The designers of native method decide a mechanism that how java application will invoke native methods. When a thread invokes a native method JVM does not create a new stack frame for that as in case of java method invocation, but it will simply dynamically link to and directly invoke the native method. 


Related Topics :

Sunday, April 5, 2015

JVM Architecture


In this tutorial we will see how a java program executes (high level) with various components of JVM.

Once you write any java program in .java file that is called Java source file. Java source file converted to Class file (.class) file by compiler using javac command. This Class file given as input to JVM which is responsible to load and execute this class file.                 




Further this class file acts as input to class loader sub-system. This sub-system is responsible for loading, linking and initialization of classes. To load/execute some memory must be required. The Cass file dumped into memory area (method area) which further communicates to execution engine. Memory areas communicate with class loader sub-system. Immediately after loading verification process starts in which byte code verifier verifies whether generated byte code is proper or not,  means generated by valid compiler or not (or is it a virus). After this Prepare process starts. In this process, for static variable memory is allocated and assigned with default values (whereas original values for static variables are stored during initialization process). Then in resolve process all symbolic references are replaced with original references from method area. After this initialization starts which assigns original values to static variables and static blocks executed. After initialization class loading completed successfully by class loader sub-system. Further, execution engine is responsible to execute the program. During executing java program execution engine may require native libraries. These native method libraries are provide by Java Native Interface (JNI)



Various memory areas present inside JVM are:

  1.  Method area – contains class level data (Static variables / blocks etc). This method area is shared among all Java Virtual Machine threads.
  2. Heap area – by default object level data will be saved (object and corresponding instance variables, arrays etc).  There is only one heap inside a Java virtual machine instance, all threads share it.
  3. Stack area – All local variable will be stored in corresponding runtime stack. For every thread a separate runtime stack will be created. Each and every method called by thread will be stored in corresponding Stack including local variables. Each entry in stack called stack frame which contains local variable array, Operand stack, frame data and Reference to runtime constant pool for class of the current method.
  4.  PC Register – Holds address of current executing instruction. If the current executing method is ‘native’, then the value of program counter register will be undefined. For every thread a separate PC registers will be created.
  5. Native method Stacks – Holds native method information. For every thread a separate stack will be created.



Following are component of JVM:

1.       Class Loader sub-system:
Class loader reads byte code and create the instance of java.lang.class , It performs three main functions of JVM, namely: loading, linking and initialization

1.       Loading : Java ClassLoader loads a java class file into java virtual machine. For this Class loader sub-system follows delegation hierarchy algoritm and uses following class loaders :
a.       Bootstrap class loader – load classes from boot strap class path (JRE/lib/rt.jar). All core java API classes are taken care by boot strap class loader
b.      Extension class loader – classes present inside ext folder (JRE/lib/ext) are taken care by extension class loader
c.       Application class loader – responsible to load classes from application level class path (environment variables class path, Manifest)
Among the class loader boot strap class loader gets highest priority. If boot strap class loader is unable to load the class then this responsibility will be taken care by extension class loader. If extension class loader fails to load the class the application class loader loads the class.
2.       Linking : Linking process consists of three sub tasks
a.       Verify
b.      Prepare
c.       Resolve
3.       Initialization – class variables are given their proper initial values
First loading happens then Linking and then Initialization

2.       Byte code verifier:
It verifies whether generated byte code is proper or not. Byte code verifier is crucial component for security.

3.       Execution Engine:  It is central component of JVM. Improve performance of the system in case of calling same method again and again. It is responsible to execute program line by line. It has two parts
1.       Interpreter - "Interpreted" means that the computer looks at the language, and then turns it into native machine language. Interpretation happens at runtime.
2.       JIT complier – Just-in-time (JIT) compiler is a program that turns Java bytecode (a program that contains instructions that must be interpreted) into instructions that can be sent directly to the processor. It has following parts :
a.       Intermediate code generator – produces intermediate code
b.      Code optimizer – responsible to optimize the code
c.       Target Code Generator – responsible to generate machine code or native code
In JIT compiler there is a component called profiler which is responsible for hotspots.

4.       Garbage collector: Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. It periodically checks for the object on heap, whose link is broken so it can collect garbage from heap.
5.       Security manager: Constantly monitors the code. It is special java object that is responsible for guarding security policies for java applications. It is always consulted before any potentially dangerous operation is requested by a java application.

Friday, April 3, 2015

Builder Design Pattern

Design Pattern > Creational Design Pattern > Builder Design Pattern

As per GOF builder pattern “Separate the construction of a complex object from its representation so that the same construction process can create different representations.”
In this pattern client application will provide parameter (used to create complex object) to builder and builder will provide the final complex object to client.
Builder pattern solves the problem of increasing parameter in object constructor. For example suppose you have created a AnimalBuilder class which create different animal objects by assembling different parts of animal as parameters passed in constructor. Parameters can be animalType, head, tail, body, leg, animalVoice, colour etc.
Public class AnimalBuilder {
                public AnimalBuilder(String animalType, AnimalHead head, String tail, String body, String leg, Voice animalVoice, String colour){
                // initializing object
    }
}
This approach is error prone, you need to be very careful about passing the parameters while creating animal object. Since most of the parameters are of same type i.e. String, So tail can be passed instead of leg or body and created animal object would look like demon ;-) .
This can be resolved using builder pattern in which there is a builder class for each animal type (builder class assembles all the animal parts), this builder pass to a director class, which ultimately creates the final animal object.
the key terms in this pattern are –
  • Builder class that specifies an abstract interface for creating parts of a Product object.
  • ConcreteBuilder that constructs and puts together parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for saving the product.
  • Director class that constructs the complex object using the Builder interface.
  • Product class that represents the complex object that is being built.
Java Implementation:
Assume that in toy factory assembly software assembles different animal parts and make a toy as final product. Implementation in builder pattern would include following classes:

/**
 * Product abstract class that holds the basic information for a product. It helps us build multiple products.
 */
package com.kmingle.builder;

public abstract class Animal{

       private String head;
       private String body;
       private String arm;
       private String leg;
       private String tail;
      
       public String getHead() {
              return head;
       }
       public void setHead(String head) {
              this.head = head;
       }
       public String getBody() {
              return body;
       }
       public void setBody(String body) {
              this.body = body;
       }
       public String getArm() {
              return arm;
       }
       public void setArm(String arm) {
              this.arm = arm;
       }
       public String getLeg() {
              return leg;
       }
       public void setLeg(String leg) {
              this.leg = leg;
       }
       public String getTail() {
              return tail;
       }
       public void setTail(String tail) {
              this.tail = tail;
       }
      
       public abstract void makeNoise();
      
       public void printAnimalDetails(){
              System.out.println(getHead());
              System.out.println(getBody());
              System.out.println(getArm());
              System.out.println(getLeg());
              System.out.println(getTail());
              makeNoise();
       }
}

/**
 * Product Class
 */
package com.kmingle.builder;

public class Lion extends Animal {
      
       @Override
       public void makeNoise() {
              System.out.println("Lion Roaring.......");
       }

}

/**
 * Product Class
 */
package com.kmingle.builder;

public class Swan extends Animal {

       @Override
       public void makeNoise() {

              System.out.println("Swan sound");
       }
      
}


/**
 * Abstract Builder class contains all the building methods to construct a general product (Animal)
 */
package com.kmingle.builder;

public abstract class AnimalBuilder {

       Animal animal;
       protected abstract void assembleAnimalHead();
       protected abstract void assembleAnimalBody();
       protected abstract void assembleAnimalArm();
       protected abstract void assembleAnimalLeg();
       protected abstract void assembleAnimalTail();
}

/**
 *  Concrete Builder Class
 */
package com.kmingle.builder;

public class LionBuilder extends AnimalBuilder {

       public LionBuilder(){
              animal = new Lion();
       }
      
       @Override
       protected void assembleAnimalHead() {
              animal.setHead("Lion's head assembled");
       }

       @Override
       protected void assembleAnimalBody() {
              animal.setBody("Lion's body assembled");
       }

       @Override
       protected void assembleAnimalArm() {
              animal.setArm("Lion's arm assembled");
       }

       @Override
       protected void assembleAnimalLeg() {
              animal.setLeg("Lion's leg assembled");
       }

       @Override
       protected void assembleAnimalTail() {
              animal.setTail("Lion's tail assembled");
       }

}


/**
 *  Concrete Builder Class
 */
package com.kmingle.builder;

public class SwanBuilder extends AnimalBuilder {

       public SwanBuilder(){
              animal = new Swan();
       }
      
       @Override
       protected void assembleAnimalHead() {
              animal.setHead("Swan's head assembled");
       }

       @Override
       protected void assembleAnimalBody() {
              animal.setBody("Swan's body assembled");
       }

       @Override
       protected void assembleAnimalArm() {
              animal.setArm("Swan's arm assembled");
       }

       @Override
       protected void assembleAnimalLeg() {
              animal.setLeg("Swan's leg assembled");
       }

       @Override
       protected void assembleAnimalTail() {
              animal.setTail("Swan's tail assembled");
       }

}


/**
 * Director Class actually drives the procedure with the necessary build parts and sequence of building an animal.
 */
package com.kmingle.builder;

public class AssemblyMachine {

       public void assembleAnimal(AnimalBuilder animalBuilder){
              animalBuilder.assembleAnimalHead();
              animalBuilder.assembleAnimalBody();
              animalBuilder.assembleAnimalArm();
              animalBuilder.assembleAnimalLeg();
              animalBuilder.assembleAnimalTail();
       }
}


/**
 * Client Class that creates dicrector and different animalbuilder objects to build final toy product
 */
package com.kmingle.builder;

public class Worker {

       public static void main(String[] args) {
              AssemblyMachine assemblyMachine = new AssemblyMachine();
             
              System.out.println("building Lion toy");
              LionBuilder lionBuilder = new LionBuilder();
              assemblyMachine.assembleAnimal(lionBuilder);
              lionBuilder.animal.printAnimalDetails();
             
              System.out.println("building Swan toy");
              SwanBuilder swanBuilder = new SwanBuilder();
              assemblyMachine.assembleAnimal(swanBuilder);
              swanBuilder.animal.printAnimalDetails();
       }

}

Out Put:
building Lion toy
Lion's head assembled
Lion's body assembled
Lion's arm assembled
Lion's leg assembled
Lion's tail assembled
Lion Roaring.......
building Swan toy
Swan's head assembled
Swan's body assembled
Swan's arm assembled
Swan's leg assembled
Swan's tail assembled
Swan sound


Now we have seen that as per Builder pattern definition AnimalBuilder Separates the construction of a complex object(Lion/Swan ) from its representation so that the same construction process(in AssemblyMachine) can create different representations(Lion/Swan etc).

Total Pageviews