Skip to content

Instantly share code, notes, and snippets.

@DanKnox
Created April 26, 2013 16:42
Show Gist options
  • Save DanKnox/5468648 to your computer and use it in GitHub Desktop.
Save DanKnox/5468648 to your computer and use it in GitHub Desktop.
Constants to set before using this function: `SEC_BTWN_GC`: Seconds before garbage collection is forced. `MIN_MEMORY_PCT`: The percentage of memory usage at which this function will actually force Garbage Collection `CRITICAL_MEMORY_PCT`: If the free memory dips below this percentage, cold fusion won't even be able to run garbage collection so w…
Calling this function:
interval = iteration at which to execute the GC cleanup. We can set this to a reasonable value and add this call right before the main outer loop that begins to process the set of Surveys. In our case we will probably set it to 1 or 2 so it runs the GC after every other survey set processing.
cleanupMemory(interval)
<cffunction name="cleanupMemory" output="true" returntype="void">
<!--- ColdFusion doesn't run garbage collection until onRequestEnd. --->
<!--- Since this is such a long running script, we must run it sooner. --->
<cfargument name="interval" required="true" type="numeric">
<cfset var runtime = "">
<cfset var freeMemoryPct = "">
<cfset var objSystem = "">
<!--- Run a quick check to see if script should stop running --->
<cfif fileExists("#getDirectoryFromPath(getCurrentTemplatePath())#\halt.txt")>
<cfset fileDelete("#getDirectoryFromPath(getCurrentTemplatePath())#\halt.txt")>
<cfthrow message="ALERT: import aborting by request at #formatDateOutput(now())#">
</cfif>
<cfif arguments.interval mod CLEANUP_INTERVAL eq 0>
<cftry>
<cfset runtime = CreateObject("java", "java.lang.Runtime").getRuntime()>
<cfset freeMemoryPct = (runtime.freeMemory()/runtime.totalMemory()) * 100>
<!--- Abort if we don't have enough memory to even run garbage collection --->
<cfif freeMemoryPct lt CRITICAL_MEMORY_PCT>
<cfthrow message="ALERT: Aborting program."
detail="Available memory is #decimalFormat(freeMemoryPct)#%.">
</cfif>
<!--- Be careful how often you call gc because it's resource intensive --->
<cfif freeMemoryPct lt MIN_MEMORY_PCT
and dateDiff('s', variables.gcCalled, now()) gte SEC_BTWN_GC
>
<cfscript>
logMsg("ALERT: Available memory is #decimalFormat(freeMemoryPct)#%.");
logMsg("ALERT: Requesting garbage collection.");
objSystem = CreateObject("java", "java.lang.System");
objSystem.gc();
freeMemoryPct = (runtime.freeMemory()/runtime.totalMemory()) * 100;
logMsg("Available memory after gc is #decimalFormat(freeMemoryPct)#%.");
variables.gcCalled = now();
</cfscript>
<cfelse>
<cfset logMsg("ALERT: Available memory is #decimalFormat(freeMemoryPct)#%.")>
</cfif>
<cfcatch type="any">
<cfset logMsg("ERROR: Garbage collection failed at #formatDateOutput(now())#.")>
<cfrethrow>
</cfcatch>
</cftry>
</cfif>
</cffunction>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment