Sunday 24 November 2013

Netbean : java.lang.OutOfMemoryError: Java heap space - Solutions

Leave a Comment
In java application development, sometimes your application will throw an exception

run:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at com.classpackage.MainConsole.main(MainConsole.java:24)
Java Result: 1 


This is because your program consuming a lot of memory. One of the solutions is to increase the Xms and Xmx argument on the project.

Lets see the example :

The Main Class

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

public class MainConsole {
    public static void main(String[] args){
        List<PhoneContacts> phoneContacts = new ArrayList<PhoneContacts>();
        // You can use diamond inference in JDK 7 like example below
        //List<PhoneContacts> phoneContacts = new ArrayList<>();
        
        for(int index = 0;index< 10000000;index++ ){
            PhoneContacts p = new PhoneContacts();
            p.setFirstName("developersnote" + Integer.toString(index));
            p.setLastName("developersnote" + Integer.toString(index));
            p.setPhoneNumber(Integer.toString(index));
            phoneContacts.add(p);            
        }        
        for(PhoneContacts p : phoneContacts){
            System.out.println(p.getPhoneNumber());
        }
    }    
}


The Phone Contacts Class

public class PhoneContacts {
    
    private String firstName;
    private String lastName;
    private String phoneNumber;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    
}


The above example will cause out of memory exception . So the solutions is to increase the argument in JVM. Lets see the solution below.

The Solutions

  1. Right click  on the java project >> properties
  2. Set the VM options -Xms512m -Xmx1024m  (You can increase the value -Xmx to the suitable maximum memory allocation depends on your project memory consumption).  
  3. Refer this post -X Command line options post for more information


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.