Skip to content

Instantly share code, notes, and snippets.

@torao
Created March 23, 2012 07:06
Show Gist options
  • Save torao/2167869 to your computer and use it in GitHub Desktop.
Save torao/2167869 to your computer and use it in GitHub Desktop.
Simple program to produce "promotion failed" GC
/**
* Simple program to produce "promotion failed" garbage collection on Oracle
* Java VM. For JDK 1.6, please execute with following extended options.
*
* java -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:ParallelGCThreads=8
* -Xmx32m -XX:NewSize=20m -XX:MaxNewSize=20m -server -verbose:gc
* -XX:+PrintGCDetails -XX:+PrintGCDateStamps PromFailed
*/
public class PromFailed {
private static class Watchdog extends Thread {
@Override
public void run(){
while(true){
try {
long tm = System.nanoTime();
sleep(100);
long millis = (System.nanoTime() - tm) / 1000 / 1000;
if(millis >= 1000){ // alert over 1sec freeze
System.out.printf("*** app frozen %.2fsec ***%n", millis/1000.0);
}
} catch(InterruptedException ex){
break;
} catch(OutOfMemoryError ex){
System.out.println("OOME caught in watchdog");
}
}
return;
}
}
public static void main(String[] args){
new Watchdog().start();
// calculate block count
final long max = Runtime.getRuntime().maxMemory();
final int size = 10; // size of 1 block
final int count = (int)(max / (size + 4)); // available block count
System.out.printf("size=%,dB, total=%,dkB, %,d blocks%n", size, max/1024, count);
byte[][] blocks = new byte[count][];
while(true){
// cleanup all blocks
java.util.Arrays.fill(blocks, null);
System.gc();
System.out.println("cleanup -------------");
// allocate blocks
try {
for(int i=0; i<blocks.length; i++){
blocks[i] = new byte[size];
}
System.out.println("fill blocks without OOME!");
} catch(OutOfMemoryError ex){
// cannot output message because heap is used fully.
// System.oui.println("fill memory");
}
// free event-indexed block
for(int i=0; i<blocks.length; i+=2){
blocks[i] = null;
}
// double-size block allocate to even-index
try {
for(int i=0; i<blocks.length; i+=2){
blocks[i] = new byte[size * 2];
}
} catch(OutOfMemoryError ex){/* */}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment