Monday, 16 May 2022

Quick guide to OutOfMemoryError in Java

OutOfMemoryError thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

 

 


OutOfMemoryError is related to Java Heapmemory. It typically occur, when the application request memory for a new object, but the heap is already full.

 

Stack vs Heap memory

Stack is a special region in computer memory, that stores temporary variables like local variables, parameters, function calls etc., Stack works in last in first out (LIFO) order. Whenever a new local variable initialized inside a function, it is pushed onto the stack, when the function finished execution, all the local variables pushed by that function onto the stack are removed from the stack. Read this post for more details.

 

Heap is a portion of memory where dynamic allocation and de allocations happen. When the application request for a new object, JVM allocates the memory in Heap. Heap memory is slightly slower to read from and written to, because pointer access is needed to access heap memory. The JVM allocates Java heap memory from the OS and then manages the heap for the Java application. Refer this post for more details.

 

Let’s write a simple program to produce OutOfMemoryError.

 

OutOfMemoryErrorDemo.java

public class OutOfMemoryErrorDemo {

	public static void main(String[] args) {
		Integer obj[] = new Integer[Integer.MAX_VALUE];

		for (int i = 0; i < Integer.MAX_VALUE; i++)
			obj[i] = i;

		System.out.println("I am done");
	}

}

 

Compile and run the above program.

$javac OutOfMemoryErrorDemo.java 
$
$java OutOfMemoryErrorDemo
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
	at OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:4)

 

How to address the OutOfMemoryError?

a. First Profile your application and try to figure out, is your application referring any unused objects, or is there any memory leaks etc., You can refer this post to find the tools to analyze your java application.

 

b. Increase the heap size. Refer this post for more details.

  

References

https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html

 

You may like

Interview Questions

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Is sqoop-import-all-tables command work with --target-dir option?

No, --target-dir is not a valid option for the command ‘sqoop-import-all-tables’.

[cloudera@quickstart Desktop]$ sqoop-import-all-tables \
> --connect "jdbc:mysql://quickstart.cloudera:3306/import_demo" \
> --username "root" \
> --password "cloudera"  \
> --target-dir /import_database_demo
Warning: /usr/lib/sqoop/../accumulo does not exist! Accumulo imports will fail.
Please set $ACCUMULO_HOME to the root of your Accumulo installation.
22/04/03 08:25:26 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6-cdh5.13.0
22/04/03 08:25:26 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
22/04/03 08:25:26 ERROR tool.BaseSqoopTool: Error parsing arguments for import-all-tables:
22/04/03 08:25:26 ERROR tool.BaseSqoopTool: Unrecognized argument: --target-dir
22/04/03 08:25:26 ERROR tool.BaseSqoopTool: Unrecognized argument: /import_database_demo

Try --help for usage instructions.

 

From the output, you can confirm that the option –target-dir is not recognized by the command ‘sqoop-import-all-tables’.

 

Previous                                                    Next                                                    Home

Get the length of longest row in a two dimensional jagged array in Java

Java support jagged arrays. A Jagged array is an array whose elements are arrays with different dimensions.

 

There are two ways to define a Jagged arrays.

a.   Specify the jagged array size using array declaration

b.   Define the array elements, let Java deduce the size

 

 

Specify the jagged array size using array declaration

 

Example

int arr[][] = new int[3][];

arr[0] = new int[2];

arr[1] = new int[6];

arr[2] = new int[4];

 

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2

b.   arr[1] of size 6

c.    arr[2] of size 4.

 

In the above example, 1st row is the longest among all the rows in the given 2-dimensional array.

 

Below snippet print the length of longest row.

int longestRow = 0;

for (int i = 0; i < arr.length; i++) {
	if (arr[i].length > longestRow) {
      longestRow = arr[i].length;
    }
}

 

Find the below working application.

 

LongestRowLength.java

 

package com.sample.app;

public class LongestRowLength {
	
	public static void main(String[] args) {
		int[][] arr = {
				{1, 2},
				{5, 6, 7, 8, 13, 14},
				{9, 10, 11, 12}
		};
		
		int longestRow = 0;
		
		for (int i = 0; i < arr.length; i++) {
			if (arr[i].length > longestRow) {
		      longestRow = arr[i].length;
		    }
		}
		
		System.out.println("Length of longest row is : " + longestRow);
	}

}

 

Output

Length of longest row is 6

 

 

 

 You may like

Interview Questions

Java: Check whether a class exists in the classpath or not

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Jagged arrays in Java

Java support jagged arrays. A Jagged array is an array whose elements are arrays with different dimensions.

 

 


There are two ways to define a Jagged arrays.

a.   Specify the jagged array size using array declaration

b.   Define the array, let Java deduce the size

 

 

Specify the jagged array size using array declaration

 

Example

int arr[][] = new int[3][];

arr[0] = new int[2];

arr[1] = new int[3];

arr[2] = new int[5];

 

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2

b.   arr[1] of size 3

c.    arr[2] of size 4.

 

Find the below working application.

 

JaggedArray1.java

package com.sample.app;

public class JaggedArray1 {

	public static void main(String[] args) {
		int arr[][] = new int[3][];
		arr[0] = new int[2];
		arr[1] = new int[3];
		arr[2] = new int[5];

		// Define array elements
		int count = 1;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				arr[i][j] = count++;
			}
		}

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
			}
			System.out.println();
		}

	}

}

Output

arr[0][0] = 1
arr[0][1] = 2

arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8
arr[2][3] = 9
arr[2][4] = 10

Define the array elements, let Java deduce the size

Example

int arr[][] = {

                  { 1, 2 },

                  { 3, 4, 5},

                  { 6, 7, 8, 9, 10}

         };

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2, and hold the elements {1, 2}

b.   arr[1] of size 3, and hold the elements {3, 4, 5}

c.    arr[2] of size 4. , and hold the elements {6, 7, 8, 9, 10}

 

Find the below working application.

 

JaggedArray2.java


package com.sample.app;

public class JaggedArray2 {

	public static void main(String[] args) {
		int arr[][] = { 
					{ 1, 2 }, 
					{ 3, 4, 5}, 
					{ 6, 7, 8, 9, 10} 
				};

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
			}
			System.out.println();
		}

	}

}

Output

arr[0][0] = 1
arr[0][1] = 2

arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8
arr[2][3] = 9
arr[2][4] = 10


You may like

Interview Questions

Call the main method of one class from other class using reflection

Java: Check whether a class exists in the classpath or not

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?

How to iterate over a two dimensional array in Java?

In this post, I am going to explain how to loop over a two dimensional array.

 

What is a multi-dimensional array?

Multidimensional arrays are the arrays of arrays.

 

Syntax to create two dimensional Array

dataType arrayName[][] = new dataType[size1][size2]

         (OR)

dataType[][] arrayName;

arrayName = new dataType[size1][size2]

 

 Example

 int arr[][] = new int[3][4];

 

Above snippet creates a 3 * 4 array, where array has 3 rows and 4 columns.

 


 

As shown in the above image,

a.   0th row and  3rd column has value 4 and it can be accessed with index notation like arr[0][3].

b.   2nd row and 1st column has value 10 and it can be access with index notation like arr[2][1].

 

Let’s see below examples to print two dimensional array content using for, while and do-while loops.

 

Using two for loops

for(int row = 0; row < noOfRows; row++) {
	for(int column = 0; column < arr[row].length; column++) {
		System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
	}
	System.out.println();
}

ArrayTraversalUsingForLoop.java

package com.sample.app;

public class ArrayTraversalUsingForLoop {

	public static void main(String[] args) {
		final int arr[][] = {
				{2, 3, 5, 7},
				{11, 13, 17},
				{19, 23, 29, 31, 37, 41}
		};
		
		final int noOfRows = arr.length;
		
		for(int row = 0; row < noOfRows; row++) {
			for(int column = 0; column < arr[row].length; column++) {
				System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
			}
			System.out.println();
		}
	}

}

Output

arr[0][0] = 2
arr[0][1] = 3
arr[0][2] = 5
arr[0][3] = 7

arr[1][0] = 11
arr[1][1] = 13
arr[1][2] = 17

arr[2][0] = 19
arr[2][1] = 23
arr[2][2] = 29
arr[2][3] = 31
arr[2][4] = 37
arr[2][5] = 41

Using while loops

final int noOfRows = arr.length;

int row = 0;
while(row < noOfRows) {
	int column = 0;
	
	while(column < arr[row].length) {
		System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
		column++;
	}
	
	row++;
	System.out.println();
}

ArrayTraversalUsingWhileLoop.java

package com.sample.app;

public class ArrayTraversalUsingWhileLoop {

	public static void main(String[] args) {
		final int arr[][] = {
				{2, 3, 5, 7},
				{11, 13, 17},
				{19, 23, 29, 31, 37, 41}
		};
		
		final int noOfRows = arr.length;
		
		int row = 0;
		while(row < noOfRows) {
			int column = 0;
			
			while(column < arr[row].length) {
				System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
				column++;
			}
			
			row++;
			System.out.println();
		}
	}

}

Array traversal using do-while loop

ArrayTraversalUsingDoWhileLoop.java

package com.sample.app;

public class ArrayTraversalUsingDoWhileLoop {

	public static void main(String[] args) {
		final int arr[][] = {
				{2, 3, 5, 7},
				{11, 13, 17},
				{19, 23, 29, 31, 37, 41}
		};
		
		final int noOfRows = arr.length;
		
		int row = 0;
		do {
			int column = 0;
			
			do {
				System.out.printf("arr[%d][%d] = %d\n", row, column, arr[row][column]);
				column++;
			}while(column < arr[row].length);
			
			row++;
			System.out.println();
		}while(row < noOfRows);
	}

}



Previous                                                 Next                                                 Home