Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, August 18, 2016

TreeMap Quick Reference

·         TreeMap object is sorted according to the natural ordering of its keys if created using default constructor( new TreeMap()), or by a  Comparator if TreeMap object is created by passing Comparator to  constructor ( new TreeMap(comparator))
·          Provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
·         If TreeMap object is created using default constructor then all keys inserted into the map must implement the Comparable interface else you will get exception while adding key-values to TreeMap instance.
java.lang.ClassCastException: xxxx cannot be cast to java.lang.Comparable
·         All keys inserted into the map must be of same type. e.g. you can’t add integer as a key into a map whose keys are String
·         Does not allows null keys, valuse can be null.
·         A TreeMap is not synchronized. Means its methods are not synchronized.
·         In multi-threaded environment, to prevent accidental unsynchronized access to the TreeMap that can modify it, wrap TreeMap using Collections.synchronizedSortedMap method
               SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
·         The iterators returned by this class's iterator methods are fail-fast. If the map is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
·         Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.

·         There are multiple ways to iterate over TreeMap

//create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","A");
    treeMap.put("2","B");
    treeMap.put("3","C");

1. Iterator using Collection values() - only iterate TreeMap's values

Collection c = treeMap.values();
Iterator itr = c.iterator();
while(itr.hasNext())
      System.out.println(itr.next());

2. Iterator using entrySet() - iterate TreeMap's keys and values in map form

for (Map.Entry entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

3. Iterator using keySet() - iterate TreeMap's keys which can be used to get values

Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
   }

Note : If the TreeMap is modified while an iteration over the collection/set is in progress (except through the iterator's own remove operation, the results of the iteration are undefined.The collection/set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.  It does not support the add or addAll operations.


·         put(K key, V value) method returns previous value associated with key, or null if there was no mapping for key. If the map previously contained a mapping for the key, the old value is replaced with new value.

Sunday, August 14, 2016

HashSet Quick Reference

  • Backed by a hash table (actually a HashMap instance)
  • While iterating HashSet the order of elements are not guaranteed
  • Offers constant time performance for the basic operations add, remove, contains and size
  • In multi-threaded environment, to prevent accidental unsynchronized access to the HashSet that can modify HashSet, wrap HashSet using Collections.synchronizedSet method

      Set s = Collections.synchronizedSet(new HashSet(...));


  • The iterators returned by this class's iterator methods are fail-fast. If the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
  • Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.
  • iterator()method returns an iterator over the elements in this set. The elements are returned in no particular order.
  • boolean add(E e) method Adds the specified element e to this set if it is not already present and return true. If this set already contains the element e then the set remains unchanged and method returns false.
  • Hashset allows one null value

Thursday, August 11, 2016

LinkedList Quick Reference

Doubly-linked list implementation of the List and Deque interfaces.
Can be used in implementing Stack and Queue as it has methods/operations like peek, poll, offer, push, pop
In multi-threaded environment, to prevent accidental unsynchronized access to the LinkedList that can modify LinkedList structurally, wrap ArrayList using Collections.synchronizedList method
List list = Collections.synchronizedList(new LinkedList(...));

The iterators returned by this class's iterator and listIterator methods are fail-fast if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.
boolean add(E e) method Appends the specified element e to the end of this list and after addition return true
boolean remove(Object o) method Removes the first occurrence of the specified element from this list and returns true if this list contained the specified element, else return false. Whereas, remove(int index) method removes the element at the specified position in this list and returns the removed element

Tuesday, August 9, 2016

ArrayList Quick Reference

It’s a Resizable-array implementation of the List interface
permits all elements, including null
equivalent to Vector, except that it is unsynchronized( i.e. it’s methods are unsynchronized)
Following operations run in constant timeget, set, iterator, listIterator
In case of add operation, adding n elements requires O(n) time
In multi-threaded environment, to prevent accidental unsynchronized access to the ArrayList  that can modify ArrayList structurally, wrap ArrayList using Collections.synchronizedList
List list = Collections.synchronizedList(new ArrayList(...));
The iterators returned by this class's iterator() and listIterator(int) methods are fail-fast if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove() or add(Object) methods, the iterator will throw a ConcurrentModificationException.
Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.
ArrayList internally implements growable dynamic array which means it can increase and decrease its size automatically. If we try to add an element to a already full ArrayList then it automatically re-sized internally to accommodate the new element
Consider a scenario when there is a need to add huge number of elements to an already full ArrayList, in such case ArrayList has to be resized several number of times which would result in a poor performance. For such scenarios ensureCapacity() method of ArrayList class is very useful as it increases the size of the ArrayList by a specified capacity.
public void ensureCapacity(int minCapacity)

toArray() mathod returns an array containing all of the elements in this list in proper sequence (from first to last element).So, this method acts as bridge between array-based and collection-based APIs.
remove(int index) method removes the element at the specified position(index) in this list. Shifts any subsequent elements to the left and return the element that was removed from the list
remove(Object o) method removes the first occurrence of the specified element from this list, if it is present and return true if this list contained the specified element else return false.

Sunday, August 7, 2016

HashMap Quick Reference

Permits multiple null values and one null key
Equivalent to Hashtable, except that it is unsynchronized( i.e. it’s methods are unsynchronized) and permits nulls (Hashtable does not allows null keys or values)
Does not guarantee that the order of map will remain constant over time.
Provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Iteration time is proportional to the "capacity" of the HashMap instance plus its actual size
In multi-threaded environment, to prevent accidental unsynchronized access to the map that can modify HashMap structurally, wrap HashMap using Collections.synchronizedMap
Map m = Collections.synchronizedMap(new HashMap(...));
Iterators of HashMaps are fail-fast
Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.
get() method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. However, null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null.

When duplicate key put into HashMap, put() method overrides old value with new value and returns the old value. put() method returns null if this map contains no mapping for the key. However, a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null.

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.

Total Pageviews