Simple program:
public class SleepTest {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(60 * 1000);
}
}
Then
$ javac SleepTest.java
$ java -cp . SleepTest
For OpenJDK 1.6.0_20 this uses 600M of virtual memory on my machine! That is, "top" shows "VIRT" 600M and RES 10m. (I am on Ubuntu 10.04, 32-bit or 64-bit).
For Sun's Java 1.6.0_22 it uses 400M of virtual memory.
What is using all that virtual memory, and how do I lower that usage?
Full "java -version":
OpenJDK:
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.4) (6b20-1.9.4-0ubuntu1~10.04.1)
OpenJDK Client VM (build 19.0-b09, mixed mode, sharing)
Sun:
$ /usr/lib/jvm/java-6-sun-1.6.0.22/jre/bin/jav -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
Edit:
Compiling with javac from either package doesn't seem to help.
Adding some code to print used memory is as follows:
private static String megabyteString(long bytes) {
return String.format("%.1f", ((float)bytes) / 1024 / 1024);
}
private static void printUsedMemory() {
Runtime run = Runtime.getRuntime();
long free = run.freeMemory();
long total = run.totalMemory();
long max = run.maxMemory();
long used = total - free;
System.out.println("Memory: used " + megabyteString(used) + "M"
+ " free " + megabyteString(free) + "M"
+ " total " + megabyteString(total) + "M"
+ " max " + megabyteString(max) + "M");
}
shows
Sun:
Memory: used 0.3M free 15.2M total 15.5M max 247.5M
OpenJDK:
Memory: used 0.2M free 15.3M total 15.5M max 494.9M
even with -Xmx5m, so it must have a minimum? I've read about defaults before (depends on jvm, virtual machine, a common strategy by default one quarter of physical memory), but is that causing the large virtual memory use and can I not decrease it?
Edit #2:
Adding -Xmx changes things:
$ java -Xmx5m -cp . SleepTest
OpenJDK:
$ java -Xmx5m SleepTest
Memory: used 0.2M free 4.7M total 4.9M max 5.8M
uses "only" 150M of virtual memory for either JVM.
Edit #3:
nos, bestsss, Mikaveli, and maybe others pointed out that virtual memory does not use swap. nos claims the OOM killer is smart enough to go by real memory usage. If those things are true, then I guess I don't care about virtual memory usage. RES (resident size) is small, so I'm good.
Edit #4:
Not sure which answer to accept. Either of these, if it shows up as an answer: "Don't worry about it because virtual memory is cheap" or some explanation of why Java reserves at least 150M in virtual memory no matter what -Xmx or -Xms I give it, even though real memory usage is tiny.
Edit #5:
This is a dup. I voted to close.