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

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

Posted by in Eclipse, Java | 2 comments

 
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

How to create a Servlet with Eclipse and Tomcat server

Posted by in Eclipse, Servlet

 

Environment Used

 

  • JDK 7 (Java SE 7)
  • Eclipse JUNO IDE
  • Apache Tomcat 7.x
  • Servlet 3

 

Setting up development environment

 
To install Eclipse IDE and to configure Apache Tomcat read this page

Creating Dynamic Web Project

 
Start your Eclipse and then go with File > New > Dynamic Web Project and enter project name as HelloWorldServlet and set rest of the options as given in the following screen:
 
creating-dynamic-web-project-eclipse-2
 
You will see the Dynamic web project in the ‘Project Explorer’ view.
 

Creating Servlet

 
Right click on src or Project -> New -> Servlet
 

  • Enter the Java package name as com.servlets
  • Enter the Class name as HelloWorldServlet
  • Click on ‘Finish’

 
creating-servlet-eclipse
 
Thats all on how to create a servlet in eclipse, in our next article we shall learn to implement Hello world example using Servlet.
 

Read More

How to install Eclipse IDE and configure apache tomcat

Posted by in Eclipse, Tomcat

 

Downloading Eclipse

 
If you need to install Eclipse, you can download it from this location: http://www.eclipse.org/downloads/
 

Installing Eclipse

 
Once downloaded extract the files in the desired directory. When you extract the file, it creates a sub directory called “eclipse” in which you can find the eclipse.exe application. You can double click on this to launch Eclipse.
 
Eclipse
 

Setup Apache Tomcat :

 
You can download the latest version of Tomcat from http://tomcat.apache.org/. Once you downloaded the installation, unpack the file into a desired directory. For example in D:\Study\Java\apache-tomcat-7.0.23
 
Now open Eclipse IDE and make sure you are in Java EE perspective; Now right click -> New -> Server in “Servers” area.
 
Create server in Eclipse
 
Now you could see list of servers that can be configured in Eclipse. You will find Tomcat v7.0 Server under “Apache” folder as shown below.
 
Ecplise tomcat server configuration
 
Click next, and fill in your Tomcat installation directory:
 
Tomcat installation folder
 
Click Finish, now the configured Apache Tomcat Server will be displayed in the “Servers” view as shown below.
 

Start Server

 
Now start and stop it to ensure that it is working properly.
 
Starting Tomcat
 
That’s all on how setup eclipse IDE and configuring apache tomcat.
 

Read More
Page 1 of 212