private static void runGCTillStable ( ) { // Possibly add another iteration in here to run this whole method 3 or 4 times. long usedMem1 = usedMemory ( ) ; long usedMem2 = Long . MAX_VALUE ; // Repeatedly garbage collection until the used memory count becomes stable, or 500 iterations occur. for ( int i = 0 ; ( usedMem1 < usedMem2 ) && ( i < 500 ) ; i ++ ) { // Force finalisation of all object pending finalisation. RUNTIME . runFinalization ( ) ; // Return unused memory to the heap. RUNTIME . gc ( ) ; // Allow other threads to run. Thread . currentThread ( ) . yield ( ) ; // Keep the old used memory count from the last iteration and get a fresh reading. usedMem2 = usedMem1 ; usedMem1 = usedMemory ( ) ; } }
Repeatedly runs the garbage collector and finalization method of the JVM runtime system until the used memory count becomes stable or 500 iterations occur whichever happens soonest . If other threads are active then this method is not likely to work as the used memory count will continually be changing .