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

 
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

Solution for “Could not create the Java Virtual Machine” issue

Posted by in Eclipse, Java | 1 comment

 
If you get the below error message while executing java program
 

Error:Could not create the Java Virtual Machine.
Error:A fatal exception has occurres.Program will exit.

 

 
To resolve this issue, following steps are needed to be followed (on Windows XP, Windows 7, Windows 8):

  • Right Click on My Computer Icon and click on Properties
  • Click on Advanced Systems Settings
  • Then Environment Variables
  • Under System Variables, click New
  • In which give Variable Name as: _JAVA_OPTIONS
  • Variable Value: -Xmx1024m
  • Click OK

That’s it, now your Java program should execute properly.

 
Note:
Heap size allocated by the JVM by default can be Increased/Modified by using Java -Xmx/s command line options.

Where
-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size

 

Click here to know about getting JVM heap size, used memory, total memory using Java Runtime programatically.
 

Read More

How to increase JVM heap size in Eclipse

Posted by in Eclipse, Java, Jboss, Tomcat | 1 comment

 
To avoid getting java.lang.OutOfMemoryErrors, while running web application, we should increase heap size allocated by the JVM by using command line options.
 

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

 

To do this, follow these steps:

1. Open the Server Configuration in Eclipse by double-clicking on the Server instance.
 
Server
 

2. Click on “Open launch configuration” link
 
Increase JVM max heap size eclipse
 
3. Click on the Arguments tab and add the following command at the end of VM arguments: -Xms128m –Xmx1024m.
 
Increase JVM max heap size eclipse
 

These values may vary, depending on requirement/available memory

 
If you are not using any server, you can type the following on the command line before you run your program:

java -Xms64m -Xmx1024m MyProgram

 

Note:

  • Do not set -Xmx to too small value
  • Set -Xms to a small value

Setting -Xmx to small value mostly leads to OutOfMemoryErrors, because this is the maximum amount of memory you are allocating for Java and it cannot utilize memory beyond the set value.

Also If you set -Xms to higher value you might run out of memory. So try to keep it to a small value like -Xms16m.
 

Read More

Eclipse Shortcuts for fast coding

Posted by in Eclipse | 1 comment

 
eclipse shortcut


List of some Shortcuts for fast coding. Traverse below and improve your coding speed by utilizing Eclipse Shortcuts.

dwd2
Download It – eclipse.pdf

 

File navigation  Short cuts
 

Short cuts Description
Alt + Shift + nUse this shortcut key to open an new menu.
Ctrl + n  Use this  shortcut key to create a new file
Ctrl+HIf you want to search in your program and work space use this short cut .
CTRL + SHIFT + ROpen a resource. You need not know the path and just part of the file name is enough.
Ctrl +EOpen a file (editor) from within the list of all open files.
CTRL + PAGE UP or PAGE DOWNGo to previous or next edit positions from editor history list.
ALT + <- or ALT + ->If you want to close the all file in editor use this shortcut key.
Ctrl +WIf you want to close the all file in editor use this shortcut key.
Ctrl +Shift+WIf you want to close the all file in editor use this shortcut key.
F2,Alt +Shift+RIt is use for re-name  file .
Ctrl +Shift +GFind the reference variable in workspace.

 

Java Editing Short cuts
 

Short cutsDescription
Ctrl+Shift+FThis short cut use to formatting  the code .
Ctrl+SpaceType assist
Ctrl+ODisplays every one of the methods and variables in addition to methods available in the current class that’s selected.
Ctrl+Shift+O                                                            This Shortcut use for Organized  import .
Ctrl+Shift+UFind the reference of a file .
Ctrl+/,Ctrl+7Single Line comment .
Ctrl+Shift+/Add block Comment .
Ctrl+Shift+\Remove the block comment.
F3Go to the declaration of the variable
F4Show the type hierarchy of an class.
Ctrl+TShow the inheritance tree of current token .
Shift+f2Show the Java Doc for current  token.
Alt Shift ZAdd the try and catch block

 
Editing Short cuts
 

Short cutsDescription
F12Focus on current editor
Ctrl +LFind the Line number.
Ctrl+D                                     This short cut use for delete the single row.
Ctrl +MThis short cut use for maximize and minimize the editor.

 
 
Debug and  Run Eclipse short cuts
 

Short cuts                                                    Description
F11Start the Debug .
Ctrl+F11Run the last program or project.
Ctrl .Or ,To Navigate  the next and previous error .
F5Step Into.
F6Step Over.
F8Resume .
Ctrl+Q Add Inspect
Ctrl +1Quick fix code.

 
Some Extra Short cuts
 

Short cuts                                                    Description
Alt +Shift +BAdd the toggle breakpoint .
Alt +Shift+cChange the method signature .
Alt +Shift+S,RGenerate the setter and getter method .
Alt +Shift+X,JRun As java Application .
Alt +Shift+X,RRun As web application .
Alt +EnterShow The Property.
Alt +Shift+X,ARun As Applet .

 
String to StringBuffer /StringBuilder
 
In order to change the concatenation from String to StringBuffer /StringBuilder, move the cursor to the String variable, and press Ctrl +1, and select ‘Use StringBuffer//StringBuilder for string concatenation’
For eg, String s = “a”+”b”+”c”+”d”;
will change to StringBuffer sB = new StringBuffer();
sB.append(“a”);
sB.append(“b”);
sB.append(“c”);
sB.append(“d”);
String s = sB.toString();
 

Read More

Debugging java application in Eclipse

Posted by in Eclipse, Java

 

5 practical Java debugging tips

 
Let’s see some common java debugging tips in eclipse.
 
1) Use conditional breakpoint
 
Eclipse allows you to setup conditional break point for debugging, which is a breakpoint with condition and your thread will only stop at specified line if condition matches instead of just stopping on that line like in case of line breakpoint. To setup a conditional breakpoint just double click on any line where you want to setup a breakpoint and then right click –> properties and then insert the condition. Now program will only stop when that particular condition is true.

 

1

 
2

 
2) Use Exception breakpoint
 
You can setup Exception breakpoint based on java exception like ArrayIndexOutOfBoundException or NullPointerException. You can setup Exception breakpoint from breakpoint window and your program will stop when exception occurs.

 

ecplise debug mode

 

3 ) Inspect and Watch
 
These are two menu options which is used to see the value of expression during debugging java program. To do, just select the statement, right click and inspect and it will show you the value of that statement at debugging time. You can also put watch on that condition, now its value will appear on watch window.

 
4) Step over, Step Into
 
These are simply great debugging options available in any Java IDE, extremely useful if you are debugging multi-threaded application and want to navigate step by step.
 
5) Suspending and resuming thread
 
You can suspend and resume any thread while debugging java program from debug window. Just right click on any thread and select either suspends or resume.
 

Read More