2

I played around a little bit with Java's arrays and I realized that a 1GB big byte array needs 4GBs RAM.
That's my code (make sure you have at least 4GB unused RAM or your PC might freeze):

public static void main(String[] args) throws InterruptedException {
    Byte[] array = new Byte[1073741823]; // Equals 1GB

    System.out.println("Done");
    Thread.sleep(10000);
    System.out.println("Completely done");
}

That's my machine:
MacBook Pro (64bit; running OS X 10.9 on it)
Java: Java SE 6 (1.6.0_65-b14-462) and Java SE 7 (1.7.0_45). RAM: 16
Used RAM: about 10GB

When I start this application, it uses 4GB instead of 1. I used these arguments to start that program: -Xmx8g -d64.

Matt3o12
  • 4,192
  • 6
  • 32
  • 47

1 Answers1

6

That's because Byte is an object, which requires enough memory to hold an object reference. You want the lower-case "byte" for the primitive type.

Scott Dudley
  • 3,256
  • 1
  • 18
  • 30
  • 5
    Wouldn't 4gb be too little for a 1GB `Byte` array though? – Benjamin Gruenbaum Jun 15 '14 at 20:38
  • Here's another good SO reference for the general objects vs primitive type question (beware auto-boxing pitfalls!): http://stackoverflow.com/questions/5199359/why-do-people-still-use-primitive-types-in-java – Scott Dudley Jun 15 '14 at 20:45
  • @Benjamin Gruenbaum: 4gb is too little for a 1gb capital-B Byte array, but it should be plenty of room for a 1gb byte array. – Scott Dudley Jun 15 '14 at 20:50
  • @ScottDudley so why does it only take 4gb in this case? – Benjamin Gruenbaum Jun 15 '14 at 20:59
  • 3
    @benjamin-gruenbaum You mean: why does the 1 million capital-B Byte array only require 4gb instead of 8gb? In theory, a million object references on a 64-bit JVM should require 8 bytes * one million = 8gb. But later versions of the Oracle JVM use [Compressed Oops](https://wikis.oracle.com/display/HotSpotInternals/CompressedOops) by default, which reduces memory consumption significantly. If you turn off Compressed Oops by rerunning the program with `-XX:-UseCompressedOops`, it will suck up the 8gb you expected. – Scott Dudley Jun 16 '14 at 00:46
  • Most JVMs use 32-bit references even on 64-bit JVMs. Each reference is typically 4 bytes. https://wikis.oracle.com/display/HotSpotInternals/CompressedOops – Peter Lawrey Jun 16 '14 at 07:00