|
Memory Management
Part:
1
2
This chapter explains:
- Overview
- Out of Memory Error
- Garbage Collection
Overview
Generally, a JVM is using the following rules to manage memory:
- When a JVM is invoked to run an application, it will ask the operating system
for enough memory to run the JVM itself and some free memory for the application
to create new objects.
- When a new object is created, the JVM will allocate memory for that object out
of the free memory area.
- When the free memory area is getting too small, the JVM will ask the operating
system for more.
- When a object is no longer used by the application, it will be destroyed. Its
memory will be freed up and merged back to the free memory area.
- When the free memory area is used up, and there is no more additional memory
available from the operating system, the JVM will stop the application and issue
the "Out of memory error".
Out of Memory Error
I wrote the following program to try to push JVM for more memory in a loop:
/**
* MemoryCrash.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
class MemoryCrash {
public static void main(String[] a) {
int max = 100;
Runtime rt = Runtime.getRuntime();
Object[] arr = new Object[max];
for (int n=0; n<max; n++) {
System.out.println("Having "+n*10+" MB and adding 10 MB...");
arr[n] = new long[10*1024*128];
System.out.println(" Free memory: " + rt.freeMemory());
System.out.println("Total memory: " + rt.totalMemory());
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
System.out.println("Interreupted...");
}
}
}
}
Output on HotSpot Client 1.6.0 VM with -Xms2m -Xmx64m
C:\>\progra~1\java\jdk1.6.0_02\bin\java -Xms2m -Xmx64m
MemoryCrash
Having 0 MB and adding 10 MB...
Free memory: 1907072
Total memory: 12521472
Having 10 MB and adding 10 MB...
Free memory: 8421336
Total memory: 29528064
Having 20 MB and adding 10 MB...
Free memory: 6210456
Total memory: 37826560
Having 30 MB and adding 10 MB...
Free memory: 14484288
Total memory: 56606720
Having 40 MB and adding 10 MB...
Free memory: 3998512
Total memory: 56606720
Having 50 MB and adding 10 MB...
Exception in thread "main" java.lang.OutOfMemoryError:
Java heap space at MemoryCrash.main(MemoryCrash.java:12)
Output on HotSpot Client 1.4.0 VM with -Xms2m -Xmx64m
Having 0 MB and adding 10 MB...
Free memory: 1897344
Total memory: 12521472
Having 10 MB and adding 10 MB...
Free memory: 8463216
Total memory: 29573120
Having 20 MB and adding 10 MB...
Free memory: 6275936
Total memory: 37871616
Having 30 MB and adding 10 MB...
Free memory: 14644240
Total memory: 56725504
Having 40 MB and adding 10 MB...
Free memory: 4157184
Total memory: 56725504
Having 50 MB and adding 10 MB...
Exception in thread "main" java.lang.OutOfMemoryError
(Continued on next part...)
Part:
1
2
|