Alex Rivera | Logout

Java char array seems to need more than 2 bytes per char

Asked 2013-06-27T13:40:13.613
15

When I run following program(running with "java -Xmx151M -cp . com.some.package.xmlfun.Main") :

package com.some.package.xmlfun;
public class Main {

    public static void main(String [] args) {
        char [] chars = new char[50 * 1024 * 1024];

    }
}

I need to increase maximum memory to at least 151M (-Xmx151M). Accordingly, when I increase array size the limit needs to be increased:

  • 50 * 1024 * 1024 -> -Xmx151M
  • 100 * 1024 * 1024 -> -Xmx301M
  • 150 * 1024 * 1024 -> -Xmx451M

Why does it looks like java needs 3 bytes per char, instead of 2 bytes as documentation suggests?

Also when I similarly create array of long it seems to need 12 bytes per long, instead of 8, with int it needs 6 bytes instead of 4. Generally it looks like it needs array_size * element_size * 1.5

Compiling with - javac \com\som\package\xmlfun\\*java

Running with - java -Xmx151M -cp . com.some.package.xmlfun.Main

Edit
Report

1 Answer

6

In Java HotSpot VM, heap is divided into "new generation" and "old generation". The array must be in either of them. The default value of ratio of new/old generation sizes is 2. (Which actually denotes old/new=2)

So with some simple math it can be shown an 151MB heap can have 50.33MB new generation and 100.67MB old generation. Also an 150MB heap has exactly 100MB of old generation. Your array + everything else (such as args) will exhaust the 100MB, hence produce OutOfMemoryError.


I tried to run with

java -Xms150m -Xmx150m -XX:+PrintGCDetails Main > c.txt

And from c.txt

(...)
Heap
 PSYoungGen      total 44800K, used 3072K (addresses...)
  eden space 38400K, 8% used (...)
  from space 6400K, 0% used (...)
  to   space 6400K, 0% used (...)
 ParOldGen       total 102400K, used 217K (...)
  object space 102400K, 0% used (...)
 PSPermGen       total 21248K, used 2411K (...)
  object space 21248K, 11% used (...)

The spaces are not exactly equals to my calculations, but they are near.

answered 2013-06-27T14:04:57.017

Your Answer