Pages Navigation Menu

Coding is much easier than you think

Java Heap Dump Analysis using Eclipse Memory Analyzer (MAT)

Posted by in Core Java, Eclipse, Java, JVM, Software | 1 comment

 
In this article we will learn what a Java heap dump is and how to analyze a heap dumps generated through OutOfMemoryError using Memory Analyzer in Eclipse.
 

What is a heap dump?

 
A heap dump is a snapshot of memory at a given point in time. It contains information on the Java objects and classes in memory at the time the snapshot was taken.
 

Why would we want to read heap dump?

 
If your Java application crashes with an OutOfMemoryError it is possible to automatically get a heap dump to analyze. This view into the memory profile of the application at the time it crashed can help us to figure out what caused the error. This can help decide what to optimize in our code.
 

How to get a heap dump?

 
To generate heap dump we have to execute a JVM with the following parameters in eclipse
 

-XX:+HeapDumpOnOutOfMemoryError writes heap dump on first  OutOfMemoryError

 

Here the heap dump will be generated in the “current directory” of the JVM by default. It can be explicitly redirected with
 

-XX:HeapDumpPath= for example -XX: HeapDumpPath=/disk/myFolder.

 
GC_Heap Dump analysis_Run_Configuration
 
GC_HeapDump anaylysis_Run_Configuration_JVM
 

How to read a heap dump?

 
Heap dump will be in binary format so you don’t read the plain file. Instead use a tool like Memory Analyzer Tool.
Download MAT plugin from this location, and install it in your eclipse.
 

OOM Java program

 

Here the Java program below is used to trigger an OutOfMemoryError. This program is basically creating multiple String instances within a List data structure until the Java Heap depletion.
 

package com.simplecode.heap;

import java.util.ArrayList;
import java.util.List;

public class OOMHeapGenerator
{
public static void main(String[] args)
{
	System.out.println("JVM OutOfMemoryError Simulator");
	List<String> leakingVariable = new ArrayList<String>();
	
	try
	{
		while (1 < 2)
		{
		leakingVariable.add("OutOfMemoryError");
		}
	}
	catch (Throwable exp)
	{
	     if (exp instanceof java.lang.OutOfMemoryError)
	     {
	     System.out.println("OutOfMemoryError triggered! " + "[" + exp + "]");
	     }
	     else
	     {
	     System.out.println("Other Exception! " + "[" + exp + "]");
	     }
	}
	System.out.println("Simulator done!");
}
}

 

On running this program, when the JVM ran out of memory it created a heap dump file java_ pid1244.hprof.
 
GC_Heap Dump Analysis_Run_Java_Program_Exec
 
Press F5 in your project folder, so now the generated heap dump file will appear in eclipse.

 
Eclipse Heap Dump Memory Analyser
 

Load Heap Dump

 
Just double click on the heap dump file and select the Leak Suspects Report, and then this file will be loaded into MAT.
 
GC_Heap_Dump_analysis_Leak Suspect Report Using MAT
 

On clicking finish the following Screen is obtained
 
GC_Heap_Dump_analysis_Chart
 

Analyze Heap Dump

 
Clicking on the “See stacktrace” link will give you the exact line of code that was building up the huge List causing the application to crash.

 
GC_Heap_Dump_analysis _Stacktrace
 

Now we know where to go look in at the code to fix this bug. Hence by analysing the Heap Dump using the MAT we could easily identify our primary leaking Java class and data structure.

 

Read More

How to find the JDK target version from a .class file?

Posted by in Core Java, Java

 
This tutorial gives a tip to find out the JDK compiler target version from a .class file
 

javap -verbose YourJavaClass

 

On running the above command in command prompt, it displays the major version number, based on which the JDK Compiler version can be determined.
 
Below are some example values:
 

JDK 1.0 -> major version 45
JDK 1.1 -> major version 45
JDK 1.2 -> major version 46
JDK 1.3 -> major version 47
JDK 1.4 -> major version 48
JDK 5   -> major version 49
JDK 6   -> major version 50
JDK 7   -> major version 51

 

Read More

Get bytearray from pdf URL in java

Posted by in Core Java, Java

 
Below code converts pdf from URL to byteArray
It need common-httpClient.jar from apache HttpComponents .
Download link – http://hc.apache.org/downloads.cgi
 

String url= "http://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf";
byte[] byteArray = null;
HttpClient httpClient =null;
	{
	try
	{
	httpClient =new httpClient();
	httpGetmethod =new GetMethod(url);
	httpGetmethod.setFollowRedirects(true);
	byteArray = httpGetmethod.getResponseBody();
	}
	catch (Exception ex)
	{
	System.out.println("Error Logs "+ex);
	}
	finally()
	{
		if(httpGetmethod !=null)
		{
		httpGetmethod.releaseConnection();
		}
	}
			
	System.out.println("ByeArray Generated"+new XStream().toXML(byteArray));
}

 

Read More

Differences between Comparator and Comparable

Posted by in Core Java, Java | 2 comments

 
One of the common asked interview question “What are differences between Comparator and Comparable”? Or “How will you sort collection of employee objects by its id or name”.
 
For this we can use two interfaces, Comparator and Comparable. Before we actually see differences, let me give you brief introduction of both.
 
Comparable interface:
 
Comparable is an interface from java.lang package. It includes only one abstract method compareTo() that is to be overridden by the programmer with his ordering code.

A comparable object (a class which implements Comparable interface) compares itself with another object. If the object obj1 would like to compare with obj2, call compareTo() method with obj1 and pass obj2 as parameter (like equals() method in case of strings).

The class which would like to sort the objects using Comparable must implement Comparable interface.
 
Comparator interface:
 
Comparator is an interface from java.util package. It includes two abstract methods – compare() and equals().

A comparator object (a class which implements Comparator interface) can compare any two objects and these two objects are passed as parameters to compare() method. That is, two objects of an Employee, like emp1 and emp2 can be passed.

The class which would like to sort the objects using Comparator must implement Comparator interface.
 
Recommended Article

 
Signature of the methods existing in Comparable and Comparator interfaces
 
java.lang.Comparable interface

  • int compareTo(Object obj2): Compares two objects. With one object (current object, say obj1) the method is called and the other is passed as parameter (like obj2). The method returns an integer value depending on the objects under comparison as follows.

java.util.Comparator interface

  • int compare(Object obj1, Object obj2): Objects obj1 and obj2, under comparison, are passed as parameters. Returns an integer value depending on the objects under comparison as described below.

Both methods returns

a) A positive integer if obj1 is greater than obj2.
b) Zero if obj1 and obj2 are equal.
c) A negative integer if obj1 is less than obj2.
 
How to use the methods?
 
Since these methods are abstract, they must be overridden by the implementing classes.

The Comparable object is used along with Collections.sort(List) and Arrays.sort(Object[]) methods.

The Comparator object is used with Collections.sort(List, Comparator) and Arrays.sort(Object[], Comparator) methods.

 

1. A program using Comparable interface
 

import java.util.*;

class Employee implements Comparable<Employee> {
	private int salary;
	private String name;

	public Employee(int salary, String name) {
		this.salary = salary;
		this.name = name;
	}

	public int getSalary() {
		return salary;
	}

	public String getName() {
		return name;
	}

	public int compareTo(Employee emp) {
		return this.salary - emp.salary;
	}
}

public class EmployeeSortBySalary {
	public static void main(String args[]) {
		ArrayList<Employee> employeeList = new ArrayList<Employee>();
		employeeList.add(new Employee(50, "Haripriya"));
		employeeList.add(new Employee(40, "Venkat"));
		employeeList.add(new Employee(70, "Raman"));
		employeeList.add(new Employee(90, "Akathar"));
		employeeList.add(new Employee(30, "Farhan"));
		Collections.sort(employeeList);
		for (Employee emp : employeeList) {
			System.out.println(emp.getSalary() + " : " + emp.getName());
		}
	}
}

 
Output of the above program :
 

30 : Farhan
40 : Venkat
50 : Haripriya
70 : Raman
90 : Akathar

 
Explanation:
 

      class Employee implements Comparable<Employee>

 

The Employee class implements Comparable interface. Here, Comparable is designed to be generics; that is, Comparable object compares only Employee objects.

Two member variables salary and name are declared and values are assigned through a constructor. Two getter methods are declared with which Employee salary and name are retrieved later.

 

public int compareTo(Employee emp)
{
 return this.salary - emp.salary;
}

 

The Comparable interface’s abstract method compareTo() is overridden where salary are compared.

Another class EmployeeSortBySalary is created which creates some Employee objects and adds them to ArrayList employeeList.

 

Collections.sort(employeeList);

 

The ArrayList object employeeList is passed to sort() method of Collections class. The sort() method sorts as per the Comparable interface compareTo() method as Employee class implements Comparable interface.
 
Sorting with name(String) field

Now let us try sorting with name field. Just change the compareTo() method in Employee class as follows.
 

// compareTo() belongs to Comparable interface
public int compareTo(Employee emp1)
{
// compareTo() belongs to String class
return this.name.compareTo(emp1.name);
}

Here, you may get a little confusion between the two compareTo() methods used in the above code. The compareTo() method used inside (this.name.compareTo(emp1.name)) belongs to String class and not Comparable interface. compareTo() method of String class makes lexicographical comparison and returns three types of integers – positive, negative and 0.
 

2. A program using Comparator interface

Earlier you have seen one program “Comparator Example” where ArrayList elements are sorted. For a better understanding of the subject, let us do the same Employee class of Comparable but with Comparator.

 

import java.util.*;

class Employee
// Note that the Employee does not implement Comparator
{
	private int salary;
	private String name;

	public Employee(int salary, String name) {
		this.salary = salary;
		this.name = name;
	}

	public int getSalary() {
		return salary;
	}

	public String getName() {
		return name;
	}
} // Note that the EmployeeSortBySalary implements Comparator

public class EmployeeSortBySalary implements Comparator<Employee> {
	

	public static void main(String args[]) {
		ArrayList<Employee> employeeList = new ArrayList<Employee>();
		employeeList.add(new Employee(50, "Haripriya"));
		employeeList.add(new Employee(40, "Venkat"));
		employeeList.add(new Employee(70, "Raman"));
		employeeList.add(new Employee(90, "Akathar"));
		employeeList.add(new Employee(30, "Farhan"));
		
		Collections.sort(employeeList, new EmployeeSortBySalary());
		for (Employee st : employeeList) {
			System.out.println(st.getSalary() + " : " + st.getName());
		}
	}

	public int compare(Employee emp1, Employee emp2) {
		return emp1.getSalary() - emp2.getSalary();
	}
}

Output :
 

30 : Farhan
40 : Venkat
50 : Haripriya
70 : Raman
90 : Akathar

 
Explanation:
 
Here in the above program, one difference you can observe is, the Comparator interface is not implemented with Employee class but with another class. But in the case of Comparable, the Comparable interface is implemented with Employee class. That is, with Comparator, we can sort any class objects without changing the original class code.
 
The code explanation is the same of earlier Comparable, but with minor changes. The method overridden is compare() (in the case of Comparable, it is compareTo()). The compare() method parameters are two objects under comparison; but with Comparable, the compareTo() method parameter is one, the other object calls the method.
 

One more difference is the usage of overloaded sort() method.

In case of Comparator, it is Collections.sort(employeeList, new EmployeeSortBySalary()). The second parameter is an object of Comparator (a class that implements Comparator).

In case of Comparable, it is Collections.sort(employeeList).
 
In our next article we shall learn about When to use Comparator and Comparable in Java

Read More

Is Java Pass by Reference or Pass by Value?

Posted by in Core Java, Java

 
Java manipulates objects ‘by reference’, but it passes object references to methods ‘by value’.
 
Consider the following program:
 

public class MainJava
{
	public static void main(String[] arg) {
		Foo f = new Foo("f");
		// It won't change the reference!
		changeReference(f);
		// It will modify the object that the reference variable "f" refers to!
		modifyReference(f);
	}

	public static void changeReference(Foo a) {
		Foo b = new Foo("b");
		a = b;
	}

	public static void modifyReference(Foo c) {
		c.setAttribute("c");
	}
}

 
Recommended Article

 
I will explain this in steps:

  1. Declaring a reference named fof type Fooand assign it to a new object of type Foowith an attribute "f".
     
    Foo f = new Foo("f");

     

    Simple reference

  2. From the method side, a reference of type Foowith a name ais declared and it’s initially assigned to null.
     
    public static void changeReference(Foo a)

     
    new reference

  3. As you call the method changeReference, the reference awill be assigned to the object which is passed as an argument.
    changeReference(f);

     
    assign referrence

  4. Declaring a reference named bof type Fooand assign it to a new object of type Foowith an attribute "b".
    Foo b = new Foo("b");

     
    new reference 2

  5. a = b is re-assigning the reference aNOT fto the object whose its attribute is "b".
    That is Only the references of a is modified, not the original ones(Reference of fremains the same)

    re assign referrence

  6. As you call modifyReference(Foo c)method, a reference cis created and assigned to the object with attribute "f".
     
    change value by
  7. c.setAttribute(“c”); will change the attribute of the object that reference cpoints to it, and it’s same object that reference fpoints to it.
     
    change value

I hope you understand now how passing objects as arguments works in Java :)

 

Read More

When to use Comparator and Comparable in Java?

Posted by in Core Java, Java

 
In our previous article we have learnt about the differences between Comparator and Comparable, In this post let’s see some best practices and recommendation on when to use Comparator or Comparable in Java:

Please consider the below point if you are about to perform sorting.

1) If the object is sorted by single way then it should implement Comparable interface, for example, let’s assume you have a Student bean class which has name, rank and id as member variable. In this case if you are about to perform sorting only by using id then you can go for Comparable interface.

On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. For example if you want to sort all the fields in the Student bean class (i.e. sort by name, rank or id) then you should go for Comparator interface.

2) Some time you write code to sort object of a class for which you are not the author, or you don’t have access to code. In these cases Comparator is only way to sort those objects as you cannot implement Comparable.

3) When you use Comparator you can name each implementation with the way you want to sort things, for example if you are writing Comparator to compare two Students based upon their rank then we can name that comparator as RankComparator, on the other hand by using Comparable interface we can’t give unique name to it.

 
Recommended Article

 

Read More