Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Memory usage of byte and long variable.

sriram sundararajan
Ranch Hand
Posts: 43
Scenario : 1

Object[] arr = new Object[100];
for (int n=0; n<max; n++) {
arr[n] = new long[10*1024*128];
}

Scenario : 2

Object[] arr = new Object[100];
for (int n=0; n><max; n++) {
arr[n] = new byte[10*1024*128];
}

Scenario 1 crashes the JVM but scenario 2 working fine. Why it is so?

regards
sri
>

Henry Wong
author
Marshal
Posts: 20902
76

Actual memory usage is implementation dependent -- but it is safe to say that, a byte takes a byte, and a long takes 8 bytes.

Henry

Rakesh Bagaria
Greenhorn
Posts: 14
could anybody explaine what is the question here??

Campbell Ritchie
Sheriff
Posts: 48440
56
Please use the Code button. I presume the >< is a misprint; I have seen it before.
You are using 100 * 10 * 128 * 1024 * 8 (= 1.048576e9) bytes at least if you use longs and 1.31072e8 bytes for bytes, ie just under 1GB for one and just under 128MB for the other. Now you can work out how much memory you have at your disposal . . .

David Newton
Author
Rancher
Posts: 12617
Rakesh Bagaria wrote:could anybody explaine what is the question here??

Exactly what was asked--why does one work, and the other throws an OOME.

Rob Spoor
Sheriff
Posts: 20495
54
Let's assume arrays have no overhead.

Each byte[]/long[] has 10*1024*128 = 1,310,720 different array values. In scenario 2 each element takes 1 byte, therefore the total is 1,310,720 bytes or 1.25MB. In scenario 1 each element takes not 1 but 8 bytes, therefore the total is 8 * 1,310,720 = 10,485,760 bytes or 10MB.

Now alone this shouldn't cause an OutOfMemoryError. However, you are creating up to 100 (no idea what value max has) of these arrays. For byte[] that is 125MB. For long[] that is 1000MB, nearly 1GB.

Matt Cartwright
Ranch Hand
Posts: 152
Rob Prime wrote:
Now alone this shouldn't cause an OutOfMemoryError. However, you are creating up to 100 (no idea what value max has) ...

max <= 100 or array out of bounds exception

and it nicely fails w/ 2GB heap max

Why?

Matt Cartwright
Ranch Hand
Posts: 152

I believe in running code

Matt Cartwright
Ranch Hand
Posts: 152
just got rid of the IDE (Eclipse), gave it an extra 80m for overhead
and it works on my machine

\$ java -Xms1104m -Xmx1104m Scenarios

\$ java -version
java version "1.6.0_17"
Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
Java HotSpot(TM) 64-Bit Server VM (build 14.3-b01, mixed mode)

M

sriram sundararajan
Ranch Hand
Posts: 43
Thanks guys,