public void onBeforeAdd ( E value ) { long freeHeapSpace = RUNTIME . freeMemory ( ) + ( RUNTIME . maxMemory ( ) - RUNTIME . totalMemory ( ) ) ; // start flow control if we cross the threshold if ( freeHeapSpace < minimumHeapSpaceBeforeFlowControl ) { // x indicates how close we are to overflowing the heap long x = minimumHeapSpaceBeforeFlowControl - freeHeapSpace ; long delay = Math . round ( x * ( x * c ) ) ; // delay = x^2 * c try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } }
Block for a varying amount based on how close the system is to the max heap space . Only kick in when we have passed the percentOfHeapBeforeFlowControl threshold .