Reputation: 43
I am doing some fancy stuff, where I really need to allocate about 1 GB.
My Computer has 8GB 64 bit System, so that's not a problem.
I use -Xmx 4g
to increase my heap space, but sadly enough that doesn't work at all.
I use:
Runtime rt = Runtime.getRuntime();
long totalMem = rt.totalMemory();
long maxMem = rt.maxMemory();
long freeMem = rt.freeMemory();
double megs = 1048576.0;
System.out.println ("Total Memory: " + totalMem + " (" + (totalMem/megs) + " MiB)");
System.out.println ("Max Memory: " + maxMem + " (" + (maxMem/megs) + " MiB)");
System.out.println ("Free Memory: " + freeMem + " (" + (freeMem/megs) + " MiB)");
Which shows me:
Total Memory: 259522560 (247.5 MiB
Max Memory: 259522560 (247.5 MiB)
Free Memory: 0 (0 MiB)
I really don't know what I am doing wrong. Does anyone of you have an idea?
Thanks a lot!
Upvotes: 3
Views: 20305
Reputation: 719386
The -Xmx
option sets the maximum size of the heap. But the JVM typically starts with a smaller heap, and expands it as required.
To tell the JVM the initial size of the heap, use the -Xms
option as well; e.g.
java -Xmx4g -Xms4g ...
tells Java to us a 4g heap, and set that size from the start. Note that this doesn't necessarily cause all of that physical / virtual memory to be allocated to the process immediately. However the heap's space sizes should be set in proportion to the nominal initial size.
(As others have noted, these are atomic options; i.e. don't put a space before 4g
.)
If you know that you will need a large part of the requested heap "pretty soon", then setting -Xms
avoids (repeated) resizing of the heap during start-up. But if your -Xms
value is significantly more than you are likely to need, then you may end up using system resources unnecessarily.
Upvotes: 1
Reputation: 10433
Tell us your whole command line, I suspect you use:
java -jar file.jar -Xmx 4G
or
java -cp file.jar package.Main -Xmx 4G
Both are wrong, you can use one of the following instead:
java -Xmx4G -jar file.jar
java -Xmx4G -cp file.jar package.Main
Upvotes: 4
Reputation: 84
-Xmx4g (with no space, as has been pointed out already) will only set a maxium for the heap size not automatically assign the full amount on startup.
-Xms4g may well do this, as this sets the initial heap size.
Typically people set these as a pair on app startup. For example when launching servers using classes that generate a lot of runtime-generated classes...
-Xms256m -Xmx2048m -XX:MaxPermSize=256m
http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html
Upvotes: 1