Clearing ColdFusion memory using garbage collection when memory gets low

I have been paining over this for ages but after finally trawling the web I finally found a post which was soooo simple but very effective in clearing the consumed memory. Link to post

What I did do was take it a stage further by building it into my Application.cfc so upon each request I would check for free memory and run the garbage collection accordingly if required.

In the OnRequestStart section I added the following code (Remove the CFFILE part as that's only there so I can see when ColdFusion does clear the garbage - Plus you can alter the free memory limit depending on your personal tastes):-

    <cffunction name="onRequestStart" access="remote">
    <cfargument name="targetPage" type="String" required=true/>
        <cftry>
            <cflock name="checkMemory" type="exclusive" timeout="1" throwontimeout="yes">
                <cfset runtime = CreateObject("java","java.lang.Runtime").getRuntime()>
                <cfset freeMemory = runtime.freeMemory() / 1024 / 1024>
                <cfif freeMemory lt 100>
                    <cfset objSystem = CreateObject( "java", "java.lang.System" )>
                    <cfset objSystem.gc()>
                    <cffile action="write" output="Garbage collected at #now()#" file="c:\garbage_collection.htm">
                </cfif>
            </cflock>
            <cfcatch type="any">
                <cffile action="write" output="Garbage collection failed at #now()#" file="c:\garbage_collection_failed.htm">
            </cfcatch>
        </cftry>

      ... YOUR CODE GOES HERE ...
 
        <cfreturn true>
    </cffunction>

Now, I haven't yet evaluated any performance penalties on a live server but I'm prepared for a small hit if it stops the server running out of memory then I'm happy.

 

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.5.002. Contact Blog Owner