views:

218

answers:

6

Is there a utility (for Windows) that uses up memory so I can create a JVM "could not reserve enough space for object heap" error?

I want to use up this memory in a process outside of the JVM.

A: 

I think you can try with this one:

String s = "b";
for (int i = 0; i < 1000 000; i++) {
  s+="b";
}

Because new string will be allocated everytime the line s+="b" is run, it should run out of java heap.

vodkhang
The old strings can be garbage collected every time it runs out of heap, so a smart implementation may never give an exception with this.
Arkku
They will still have to store the resultant string. Thus, it may be worth just infinitely incrementing a given string.
DeadMG
+7  A: 

Just use the -Xms flag

java -Xms3g org.foo.Main

The above will try to create an initial heap size of 3 GB, just adjust the number so it is larger than the total memory of your system (physical & virtual)

M. Jessup
This actually won't work as you explain on 32 bit Windows boxes, or at least in the sense I think you mean. The JVM needs a contiguous address range for the heap, and Windows has a hole at 2gb. So yes, it fails, but not necessarily the box is out of memory, but rather because it doesn't fit inside a single address space.
Trent Gray-Donald
A: 
List<Object> leak = new ArrayList<Object>();
while(true) {
    leak.add(new Object());
}
LES2
A: 

You can use up an arbitrary amount of memory by running a number of scripts that look like this:

public static void main(String[] args)
{
    List<String> l = new ArrayList<String>();
    for (long i = 0 ; i < 100000000l ; i++)
    {
        l.add(new String("AAAAAAA"));
    }
}

With sufficiently large heap space (e.g. -Xmx1024M). The problem with this is that any modern OS will attempt to use virtual memory to allow the application to still function, which will cause your hard drive to thrash rather than run out of memory for the JVM. You may need to set your OS total swap space to something fixed to actually encounter this scenario.

Greg Adamski
A: 

Simple. Just set the

-Xmx50m

or something else that is way too small. Trying to suck up all the memory on the box will screw up other things including your debugging session.

Pat
A: 

Here is a tiny C program for you that will consume the number of bytes specified on the command line:

#include <stdlib.h>
int main(int argc, char *argv[]) {
  int bytes = atoi(argv[1]);
  char *buf = malloc(bytes);
  while (1) {
    int i;
    for (i = 0; i < bytes; i++) buf[i] += 1;
  }
}
Keith Randall