Sunday, 19 May 2013

How Garbage Collection works in Java

How Garbage Collection works in Java



I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article or you call tutorial about How Garbage Collection works in Java or what is Garbage collection in Java in simple word which would be easy to understand and have sufficient information to understand how garbage collection works in Java.

Garbage collection in Java TutorialThis article is  in continuation of my previous articles How Classpath works in Java and How to write Equals method in java and  before moving ahead let's recall few important points about garbage collection in java:

1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.


When an Object becomes Eligible for Garbage Collection

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.

Heap Generations for Garbage Collection in Java

Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java

Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.

3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

JVM Parameters for garbage collection in Java

Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation. In my opinion before doing garbage collection tuning detailed understanding of garbage collection in java is must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html

Full GC and Concurrent Garbage Collection in Java

Concurrent garbage collector in java uses a single garbage collector thread that runs concurrently with the application threads with the goal of completing the collection of the tenured generation before it becomes full. In normal operation, the concurrent garbage collector is able to do most of its work with the application threads still running, so only brief pauses are seen by the application threads. As a fall back, if the concurrent garbage collector is unable to finish before the tenured generation fill up, the application is paused and the collection is completed with all the application threads stopped. Such Collections with the application stopped are referred as full garbage collections or full GC and are a sign that some adjustments need to be made to the concurrent collection parameters. Always try to avoid or minimize full garbage collection or Full GC because it affects performance of Java application. When you work in finance domain for electronic trading platform and with high volume low latency systems performance of java application becomes extremely critical an you definitely like to avoid full GC during trading period.

Summary on Garbage collection in Java

1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java.

Please share with your friends if like this article

List of special bash parameter used in Unix or Linux script

Special bash parameter Meaning $! $! bash script parameter is used to reference the process ID of the most recently executed command in background. $$      $$ is used to reference the process ID of bash shell itself $#      $# is quite a special bash parameter and it expands to number of positional parameters in decimal. $0 $0 bash parameter is used to reference name of the shell or shell script. so you can use this if you want to print name of shell script. $-      $- (dollar hyphen) bash parameter is used to get current option flags specified during invocation, by the set built-in command or set by the bash shell itself. Though this bash parameter is rarely used. $?      $0 is one of the most used bash parameter and used to get the exit status of the most recently executed command in foreground. By using this you can check whether your bash script is completed successfully or not. $_ $_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking mails. $@      $@ (dollar at the rate) bash parameter is used to expand into positional parameters starting from one. When expansion occurs inside double quotes, every parameter expands into separate words. $*      $* (dollar star) this is similar to $@ special bash parameter  only difference is when expansion occurs with double quotes, it expands to a single word with value of each bash parameter separated by the first character of the IFS special environment variable.

How to create read only List, Map and Set in Java – unmodifiable example

Read only List, Map and Set in Java

Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java, as shown in below example. Any modification in read only List will result in java.lang.UnSupportedOperationException in Java.  This read-only List example is based on Java 5 generics but also applicable  to other Java version like JDK 1.4 or JDK 1.3, just remove Generics code i.e. angle bracket which is not supported prior to Java 5. One common mistake programmer makes is that assuming fixed size List and read only List as same. As shown in our 3 example of converting Array to Array List , we can use Arrays.asList() method to create and initialized List at same line. List implementation returned by this method is fixed size and it doesn’t allow adding or removal of element but it is not read only because you can update objects by calling set(index) method. How to make a collection read only is also a popular Java collection interview question, which makes this Java collection tutorial even more important.

Read only List, Set and Map Example - Java

Example to create read only List Set and Map in JavaHere is sample Java program which demonstrate method of creating read only List, Set and Map in Java. You can make any List, Set or Map implementation as read only by following code example. Just remember that Collections.unModifiableList() , Collections.unModifiableSet() and Collections.unModifiableMap() method in Java. On read only List add, remove and set operation is not permitted, on read only Set you can not add or remove elements and in read only Map you can not put new entries or update existing entries. You can use same methods to convert any List implementation like ArrayList, LinkedList or Vector to read only ArrayList , LinkedList and Vector in Java.

package example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Java program to create read only List, Set and Map in Java. You can first create
 * a List or Set and than make it unmodifiable or read-only by
 * using  Collections.unmodifiableList() or Collections.unmodifiableSet() method.
 *
 * @author Javin Paul
 */

public class ReadOnlyListSetMap {
 
    public static void main(String args[]) {            
       
        // creating List in Java
        List<String> contents = new ArrayList<String>();
     
        // initializing List in Java
        contents.add("Example");
        contents.add("Tutorial");
        contents.add("Program");
     
     
        // Currently This List is not read only, you can add or remove elements from List
        contents.add("Tips"); //should not be allowed if List is read only.
     
        System.err.println("normal List in Java : " + contents);
     
        //creating readonly List from contents
        contents = Collections.unmodifiableList(contents);
     
        //java.lang.UnsupportedOperationException -- no modification in read only list
     
       //not allowed as it is read-only List in Java
       contents.add("Can I add object into read only List - No");

       
        contents.remove("Example"); //remove not allowed in read only list
     
        //java.lang.UnSupportedOperation - List update not allowed
        contents.set(0, "Can I override or set object in read-only Set - No");

     
        //Creating read only Set in Java
        //similar to read-only List you can also create a Set which is read only
        //i.e. addition , removal and modification operation is not permitted on list
     
     
        //Creating a Set based on contents of List      
        Set<String> readOnlySet = new HashSet<String>(contents);
     
        System.out.println("original Set in Java : " + readOnlySet);

        //Set is not yet read-only you can still add elements into Set
        readOnlySet.add("Override");

        System.out.println("Set before making read only : " + readOnlySet);
     
        //making Set readonly in Java - no add remove or set operation permitted
        readOnlySet = Collections.unmodifiableSet(readOnlySet);
     
        //trying to add element in read only Set - java.lang.UnSupportedOperationException
        readOnlySet.add("You can not add element in read Only Set");
     
        //trying to remove element from read only set
        readOnlySet.remove("Example"); //you can not remove elements from read only Set
     
     
     
        // Creating read only Map in Java
        // Similar to List and Set you can also create read only or unmodifiable Map in Java
        // add , remove and override is not allowed on read only Map in Java
     
        Map<String, String> contries = new HashMap<String, String>();      
        contries.put("India", "New Delhi");
     
        //Map is not read only yet, you can still add entries into
        contries.put("UK", "London");
     
        System.out.println("Map in Java before making read only: " + contries);
     
        //Making Map read only in Java
        Map readOnlyMap = Collections.unmodifiableMap(contries);
       
        //you can not put a new entry in read only Map in Java
        readOnlyMap.put("USA", "Washington"); //java.lang.UnSupportedOperation
       
        //you can not remove keys from read only Map in Java
        readOnlyMap.remove("UK"); //java.lang.UnSupportedOperation
     
    }
 
}

That’s all on how to create read only List, Set and Map in Java. Its very easy to make any List implementation read only by wrapping it with Collections.unModifiableList(). Use same technique to convert any other Collection into read only in Java.
Other Java collection tutorial from Javarevisited

Difference between ArrayList and Vector in Java

Difference between ArrayList and LinkedList in Java

10 example of Hashtable in Java

4 ways to traverse Map in Java

How to convert ArrayList to HashSet in Java

How to sort ArrayList in ascending and descending order in Java

Please share with your friends if like this article

Top 30 Programming questions asked in Interview - Java C C++ Answers

Top 30 Programming interview questions

Programming questions are integral part of any Java or C++ programmer or software analyst interview. No matter on which language you have expertise it’s expected that you are familiar with fundamental of programming and can solve problems without taking help of API. Programming questions like How to reverse String using recursion or How to find if Array contains duplicates  are some popular examples of programming question in Java.  Programming questions present lot of challenges Especially to Java developers as compared to C++ programmer and I think, One reason for this is powerful Java API; Which has method for almost every need and you rarely need to write by your own or there are lots of third party library from Apache, Spring, Google and other open source. These programming interview questions are from my personal collections and I have only chosen those which are not very difficult, can be solved easily but at same time can become too complex or confusing, present lots of follow-up questions and test fundamentals of programming, OOPS and design. I have not given answers of these programming questions but those can be found by google and I will try to post links of answers here sometime later but at same time I will try to provide quick tips or hints on some questions.

Anyone who is following programming questions must be familiar with these questions and also knows answer for most of these but for new guys and even for intermediate its worth refreshing it before going to any programming job interview e.g. Core Java interview.

String Programming Interview Questions

String is the primary and probably most common thing you come across on any programming language and so is with any programming interview. There is almost always a question on String whether its related to length or replace but I have always find one or two String programming questions on interviews.

1) Write code to check a String is palindrome or not?
Palindrome are those String whose reverse is equal to original.This can be done by following technique demonstrated in How to reverse String in Java without using API
 

2) Write a method which will remove any given character from a String?
3) Print all permutation of String both iterative and Recursive way?

4) Write a function to find out longest palindrome in a given string?

Some more String related Questions which mostly appear in Java programming interviews:
Difference between String and StringBuffer in Java
Why String is final in Java
How to Split String in java 
Why Char array is preferred over String for storing password?

Programming questions on Array

programming questions asked in interview, programming interview questions and answersArray is one of the topics where most of programming questions is asked. There are many and many programming questions on Array and here I have included only some of them which is not very difficult to solve but some of array programming question can be extremely challenging, so well prepare this topic.

5) In an array 1-100 numbers are stored, one number is missing how do you find it?

6) In an array 1-100 exactly one number is duplicate how do you find it?
This article contains a trick to find duplicates in Array using Java programming language
 

7) In an array 1-100 many numbers are duplicates, how do you find it?

trick in this programming questions is by using hashmap or hashtable , we can store number as key and its occurrence as value, if number is already present in hashtable then increment its value or insert value as 1 and later on print all those numbers whose values are more than one.

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

Here is a quick tip to solve this programming question:  put the elements of the second array in the Hashtable and for every element of the first array, check whether it’s present in the hash or not, O/P all those elements from the first array that are not present in the hash table

9) How do you find second highest number in an integer array?

LinkedList Programming Interview Questions

10) How do you find middle element of a linked list in single pass?

To answer this programming question I would say you start with simple solution on which you traverse the LinkedList until you find the tail of linked list where it points to null to find the length of linked list  and then reiterating till middle. After this answer interviewer will ask you find the middle element in single pass and there you can explain that by doing space-time tradeoff you can use two pointers one incrementing one step at a time and other incrementing two step a time, so when first pointer reaches end of linked second pointer will point to the middle element.

11) How do you find 3rd element from last in single pass?
This programming question is similar to above and can be solved by using 2 pointers, start second pointer when first pointer reaches third place.
12) How do you find if there is any loop in singly linked list? How do you find the start of the loop?
This programming question can also be solved using 2 pointers and if you increase one pointer one step at a time and other as two steps at a time they will meet in some point if there is a loop.
13) How do you reverse a singly linked list?

Binary Tree Programming Interview Questions

Binary tree or simply tree is one of favorite topic for most of interviewer and pose real challenge if you struggle with recursion. Programming questions on tree can become increasingly difficult when you think iterative but sometime can be very easy if you come with recursive solution.
14) How do you find depth of binary tree?
15) Write code to print InOrder traversal of a tree?
16) Print out all leaf node of a binary tree?

 

Programming questions on searching and sorting

I have only included two programming questions related to searching and sorting but there are more can be finding on google. Purpose of these programming questions is to see whether programmer is familiar with essential search and sort mechanism or not.
17) Write a program to sort numbers using quick sort?

18) Write a program to implement binary search algorithm
19) How do you sort Java object using Comparator?
This is another Java specific programming questions and you can check how to sort Object using Comparator and Comparable for answer.

Programming questions on numbers

Most of the programming questions are based on numbers and these are the ones which most of us did on college level and mind you they still has value I have seen programmers with experience of 3 years struggle with these programming questions and doesn’t solve it some time and take a lot of time which simply shows that they are not in programming in there day to day work.
19) Write code to check whether a no is power of two or not?

20) Write a program to check whether a no is palindrome or not?
check out this post which shows how to reverse number in Java and can be used to find if its palindrome or not.
 

21) Write code to check whether a no is Armstrong no or not 
Here is a Java program to find Armstrong number, you can use same logic to write code in any other programming language like C and C++.
 

22) Write a program to find all prime number up to a given numbers?
Here is another Java program to find prime numbers and print them. By using logic demonstrated in this program; you can write similar program in C and C++.
 

23) Write function to compute Nth Fibonacci number? Both iterative and recursive?
Check this Java program to print Fibonacci Series using recursion and iteration.

General Programming Interview Questions

In this category of programming questions I have put questions which are not fit into any data structure but presents a real life problem and you need to provide solution. These programming questions are sometime based on problems faced by developer itself. I have not included many Software design related programming question which I have shared on Top 20 software design questions and answers; you can also check that. 

24) Write a program to find out if two rectangles R1 and R2 are overlapping?
35) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time, write a function to return number of ways to climb a ladder with n step.
26) Write code for Generate Random No in a range from min to max?
27) Write program for word-wrap which should work on any screen size?
28) Design an algorithm to find the frequency of occurrence of a word in an article?
29) Write a program to implement blocking queue in Java?

30) Write a program for producer-consumer problem?
This article solves producer consumer problem using BlockingQueue in Java. You can refer it to answer this question.

Tips on answering programming questions

1. If Interviewer asks you to write function then make sure you do some necessary check for bad input e.g. null check or empty check. Most of the time programmer forgets to test for not null, empty, less than 1, greater than 1 or zero input.
2. If you write iterative version of function then Interviewer may ask you to write recursive version or vice-versa so be prepare for that.
3. If you write a recursive function then Interviewer will ask to optimize it, even in case of Iterative version. So remember that you can optimize recursive function by Memorization (caching already calculated value) and by applying some space/time tradeoff principle. For example recursive version of Fibonacci series has O(n2) which can be reduced to O(n) using Memoziation.
4. Interviewer may ask you to calculate Order of complexity for best and worst case of any method so be prepared.

5. Most of the time Interviewer ask how to fix a problem as follow-up question e.g. he will ask how do you find deadlock and then how to fix deadlock in java etc.

Apart from these programming interview questions here are some of other java programming questions I have already discussed in my blog:

Why String is immutable in Java

How HashMap works in Java

Top 20 Core Java Interview questions
Top 10 Java Collection interview question
Top 15 multi-threading Interview question
Top 10 Java Serialization interview question

Please share with your friends if like this article

Java Program to find factorial of number in Java - Example Tutorial

How to find factorial of a number in Java on both recursive and iterative way is a common Java interview question mostly asked at fresher level. It’s not just popular on Java interview but also on other programming language like C or C++. Its also famous  In our last article we have seen how to check if a number is prime or not and in this Java programming tutorial we will see a simple Java program to find factorial of a number in Java by using recursion and iteration. Same program can also be used to print factorial of any number or printing a range of factorial as well. Let’s talk about logic, factorial of a number is calculated by formula number*(number -1) till zero and since value of factorial zero is 1, it acts as a base case in recursive version of factorial method. logic to find factorial of number is encapsulated inside factorial(int number) and fact(int number) method.

This Java programming tutorial is in next with my earlier tutorial for beginners like Java Program to reverse String in Java with recursion , Java program to free memory in java and recently  how to read and write on text file in Java etc, if you haven’t read them you may find them interesting and useful.


How to find factorial of number in Java using recursion and iteration :

How to print factorial of number in Java with ExampleIn this section we will see complete code example of Java program to calculate factorial of a number in both recursive and iterative way. If you look at closely you will find that recursive solution of calculating factorial is much easier to write and pretty intuitive to read as it represent formula number*(number -1). Any way recursion should only be limited for educational purpose as it is always subject to stack overflow error if recursion is too deep. Calculating factorial of a number is also a good programming question to exercise for anyone who is just started learning programming. Anyway here is example of Java program to find factorial of a number :

/**
 * Simple Java program to find factorial of a number using recursion and iteration.
 * Iteration will use for loop while recursion will call method itself
 */

public class FactorialInJava{

    public static void main(String args[]) {
     
      //finding factorial of a number in Java using recursion - Example
      System.out.println("factorial of 5 using recursion in Java is: " + factorial(5));
     
      //finding factorial of a number in Java using Iteration - Example
       System.out.println("factorial of 6 using iteration in Java is: " + fact(6));
    }
 
 
    /*
     * Java program example to find factorial of a number using recursion
     * @return factorial of number
     */

    public static int factorial(int number){      
        //base case
        if(number == 0){
            return 1;
        }
        return number*factorial(number -1); //is this tail-recursion?
    }
 
    /*
     * Java program example to calculate factorial using while loop or iteration
     * @return factorial of number
     */

 
    public static int fact(int number){
        int result = 1;
        while(number != 0){
            result = result*number;
            number--;
        }
     
        return result;
    }
}

Output:
 factorial of 5 using recursion in Java is: 120
 factorial of 6 using iteration in Java is: 720

That's all on how to calculate or find factorial of number in Java. Both iterative and recursive version of factorial can be used to calculate factorials but beware of StackOverFlowError if a larger number is passed to recursive version of factorial method in Java.
Other Java Programming tutorial you may like

Java Program to sort ArrayList in descending order

Java Program to loop Map in Java

Java Program to create Thread in Java

Java Program to stop Thread in Java

Java Program to parse XML file in Java using DOM

Java Program to find if array contains duplicates

Difference between throw and throws in Java

Please share with your friends if like this article

Difference between DOM and SAX Parsers in Java

Difference between SAX and DOM Parser is very popular Java interview and often asked when interviewed on Java and XML. Both DOM and SAX parser are extensively used to read and parse XML file in java and have there own set of advantage and disadvantage which we will cover in this article. Though there is another way of reading xml file using xpath in Java which is more selective approach like SQL statements people tend to stick with XML parsers. DOM Parser vs SAX parsers are also often viewed in terms of speed, memory consumption and there ability to process large xml files.


Difference between DOM and SAX XML Parser in Java

DOM XML Parser in Java

difference between DOM and XML parsers in Java

DOM Stands for Document Object Model and it represent an XML Document into tree format which each element representing tree branches. DOM Parser creates an In Memory tree representation of XML file and then parses it, so it requires more memory and its advisable to have increased heap size for DOM parser in order to avoid Java.lang.OutOfMemoryError:java heap space . Parsing XML file using DOM parser is quite fast if XML file is small but if you try to read a large XML file using DOM parser there is more chances that it will take a long time or even may not be able to load it completely simply because it requires lot of memory to create XML Dom Tree. Java provides support DOM Parsing and you can parse XML files in Java using DOM parser. DOM classes are in w3c.dom package while DOM Parser for Java is in JAXP (Java API for XML Parsing) package.

SAX XML Parser in Java

SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts. Java provides support for SAX parser and you can parse any xml file in Java using SAX Parser, I have covered example of reading xml file using SAX Parser here. One disadvantage of using SAX Parser in java is that reading XML file in Java using SAX Parser requires more code in comparison of DOM Parser.

Difference between DOM and SAX XML Parser

Here are few high level differences between DOM parser and SAX Parser in Java:
1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.
2) DOM parser is faster than SAX because it access whole XML document in memory.
3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.
4) DOM parser works on Document Object Model while SAX is an event based xml parser.
That’s all on difference between SAX and DOM parsers in Java, now it’s up to you on which XML parser you going to choose. I recommend use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you don’t know size of xml files to be processed or they are large.
Java Tutorial you may like:

Difference between SynchronizedCollection and ConcurrentCollection in Java

Difference between ArrayList and Vector in Java

Difference between Comparator and Comparable in Java

Difference between SendRedirect and Forward in Servlet and JSP

Difference between ClassNotFoundException and NoClassDefFoundError in Java

Top 10 Collection Interview Questions in Java

Difference between HashMap and HashSet in Java

Please share with your friends if like this article