1

Just how big is an Integer()? I ask because of what happened below.

I ran out of heap memory after trying to put 10^6 integers (in [0, 10^6) ) into a double-ended queue. The implementation uses a doubly-linked list and appears as

Deque<Item> implements Iterable<Item> { }

But when using Strings, I was able to finish without having to increase the size of the heap:

String hw = "Hello, world."; 

for (i=0;i<10**6;i++) {
 myDq.addToEnd(hw); 
}
user1505713
  • 615
  • 5
  • 20
  • Have you seen http://stackoverflow.com/questions/4031242/how-much-memory-is-allocated-for-one-integer-object-in-java-how-to-find-out-thi? – sushain97 Sep 07 '13 at 04:40
  • While the question is a duplicate of 4031242 on the surface, the real question seems to be why an `Integer` would cause the program to run out of heap space when a `String` -- which seems like it should be bigger -- doesn't. So I don't think it's really a duplicate, in that the linked-to question doesn't actually answer the OP's real question. – yshavit Sep 07 '13 at 05:04
  • This 10**6 is not working . how is for that – muthukumar Sep 07 '13 at 05:42
  • 1
    `10**6` is not valid Java syntax. There is no exponentiation operator in Java. – Jesper Sep 07 '13 at 07:22

1 Answers1

9

hw always references the same one object, so even though you're adding 10^6 items (and thus have ~10^6 nodes internally), you'll only have one String object allocated -- lots of references to that one object, but just that one object.

In fact, even if you did something like:

for (i=0;i<10**6;i++) {
  String hs = "Hello, world."
  myDq.addToEnd(hw); 
}

You'd only have one String because of string interning: all equal string literals across the whole JVM use the same one String object.

I suspect you'll get the same OOM if you change it a bit to:

for (i=0;i<10**6;i++) {
  String hs = new String("Hello, world.".toCharArray());
  myDq.addToEnd(hw); 
}

That allocates a new String each time, with a copy of the original String's char array.

(OOM is a common nickname for OutOfMemoryError, which is what Java throws when it's run out of heap space and can't reclaim enough through the garbage collector (GC). In this case, the list and all the objects reachable through it -- the internal node objects, the Integer or String values, etc -- can still be reached by the program and thus can't be GC'ed, so the JVM has nowhere to turn to for more heap space.)

yshavit
  • 42,327
  • 7
  • 87
  • 124