Ask Ben: ColdFusion Variable Caching And How To Use It (Simple Demo)

Posted March 28, 2007 at 6:58 PM

Tags: ColdFusion, Ask Ben

There is no particular question here. I have been asked about variable caching in ColdFusion and I felt a demo would explain what a back-and-forth email conversation could not. This is a demonstration of very simple variable caching in a small ColdFusion application. Here, we are caching a value (a Struct in this case) in the APPLICATION scope. We are then referencing it on the index.cfm page.

The demo has two pages. The first is our Application.cfm page. I used the Application.cfm rather than the Application.cfc as I feel for demonstration purposes, there is less "noise" in the Application.cfm page. Then, we have our index.cfm page. The index page merely references the cached variable and displays the data.

Application.cfm

 Launch code in new window » Download code as text file »

  • <!--- Kill extra output. --->
  • <cfsilent>
  •  
  • <!---
  • Define the application. Here, I am setting a very small
  • Application timeout (since I am on the work server) -
  • In reality, this would either be left out (using CFAdmin
  • default) or 2 days or something.
  • --->
  • <cfapplication
  • name="SimpleCacheDemo"
  • applicationtimeout="#CreateTimeSpan( 0, 0, 5, 0 )#"
  • sessionmanagement="false"
  • setclientcookies="true"
  • />
  •  
  •  
  • <!--- Set request settings. --->
  • <cfsetting
  • showdebugoutput="false"
  • />
  •  
  •  
  • <!---
  • We need to check to see if our application is
  • initialized. For convenience, I am going to store an
  • Applcation variable that flags for initialization
  • (DateInitialized). If this value does NOT yet exists
  • OR the user has flagged a reset via the URl, we are
  • going to initialize the application.
  •  
  • NOTE: By initializing the application using the
  • Application.cfm (or Application.cfc) we ensure that the
  • application get initialized no matter what page in
  • our application gets requested.
  • --->
  • <cfif (
  • (NOT StructKeyExists( APPLICATION, "DateInitialized" )) OR
  • StructKeyExists( URL, "resetapp" )
  • )>
  •  
  • <!---
  • Either a re-init of the application was requested,
  • or the app has not yet been requested. Since we
  • are potentially updating live, shared memory
  • (APPLICATION), throw a Lock on it to force a
  • single thread.
  • --->
  • <cflock
  • scope="APPLICATION"
  • type="EXCLUSIVE"
  • timeout="20">
  •  
  • <!---
  • Since we are in a multi-threaded environment,
  • it is possible that why we were locking, someone
  • else swooped in an performed the initialization
  • before we could do it. Therefore, we need to
  • perform a double-check lock (pattern) to see if
  • initialization is still required.

  • However, if we have requested a manual re-init,
  • then we are going to proceed no matter what.
  • --->
  • <cfif (
  • (NOT StructKeyExists( APPLICATION, "DateInitialized" )) OR
  • StructKeyExists( URL, "resetapp" )
  • )>
  •  
  • <!---
  • We see that, indeed, the application still
  • is not initialized (DateInitialization flag
  • has not been set). We can now safely proceed
  • with application initialization.
  • --->
  •  
  • <!---
  • Clear the existing Application to make sure
  • we don't have any old data.
  • --->
  • <cfset StructClear( APPLICATION ) />
  •  
  • <!--- Flag initialization. --->
  • <cfset APPLICATION.DateInitialized = Now() />
  •  
  •  
  • <!---
  • Now, we are going to cache some objects. For
  • now, we are simply caching built in CF data
  • types for demonstration. However, these
  • could easily be ColdFusion components (or
  • even Java objects) created using the
  • CreateObject() function.
  • --->
  •  
  • <!---
  • Cache this struct. By declaring the struct
  • directly in the APPLICATION scope, we are
  • caching in the APPLICATION scope. This
  • struct will exist for as long as the
  • Application does (or until the scope is
  • cleared or the variable is deleted).
  • --->
  • <cfset APPLICATION.Actress = StructNew() />
  •  
  • <!--- Set values in the struct. --->
  • <cfset APPLICATION.Actress[ "Christina" ] = "Cox" />
  • <cfset APPLICATION.Actress[ "Lori" ] = "Petty" />
  • <cfset APPLICATION.Actress[ "Linda" ] = "Hamilton" />
  • <cfset APPLICATION.Actress[ "Angella" ] = "Bassette" />
  •  
  • <!---
  • You could perform as much cacheing as you
  • want at this point. I am only caching one
  • object for demonstration purposes.
  • --->
  •  
  • </cfif>
  •  
  • </cflock>
  •  
  • </cfif>
  •  
  • </cfsilent>

Index.cfm

 Launch code in new window » Download code as text file »

  • <html>
  • <head>
  • <title>Simple ColdFusion Cache Demo</title>
  • </head>
  • <body>
  •  
  • <h1>
  • Here Are Your Cached Actresses (Lucky You!)
  • </h1>
  •  
  • <cfoutput>
  •  
  • <!---
  • Loop over the actresses in the struct. We can
  • reference the cached struct directly in the
  • APPLICATION. Technically we are referencing shared
  • memory, and there are those that would argue this
  • requires a CFLock to be used... however, I am of
  • the mind set that even the "worst case" scenario
  • in this case will not be bad - therefore, no lock.
  • --->
  • <cfloop
  • item="FirstName"
  • collection="#APPLICATION.Actress#">
  •  
  • <p>
  • #FirstName#
  • #APPLICATION.Actress[ FirstName ]#
  • </p>
  •  
  • </cfloop>
  •  
  • </cfoutput>
  •  
  • </body>
  • </html>

I am sure this is pure review for many of you, but it may be new to even more of you. Please let me know if any further explanation is needed.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Other Searches  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Mar 28, 2007 at 10:00 PM // reply »
26 Comments

Nicely done, Ben. One clarification: the cflock and double-check for if NOT StructKeyExists( APPLICATION, "DateInitialized" ) is *only* necessary because the StructKeyExists( URL, "resetapp" ) is included, correct? If we didn't want to allow re-initialization of the Application-scoped variables via the URL (for security reasons), then the cflock and double-check are unnecessary in CF 6.1+.


Mar 29, 2007 at 7:20 AM // reply »
7,488 Comments

@Aaron,

I actually made one small mistake. In the inner CFIF statement, I forgot to check for the manual reset. I have updated the code (see the CFIF inside the CFLock). If someone requests a manual reset, the DateInitialized IS going to be present which is why the original code wouldn't work.

And to answer your question, Yes, the double-check locking is required ONLY because of the manual reset. If this code was fired because the application was just starting up, theoretically, this would be a single-threaded environment. But actually, as I am even typing this, I am not so sure. Because these are based on page requests (the Application.cfm does not get processed until a page is requested) then I actually don't see why two simultaneous requests couldn't cause conflicts - see, checking for DateInitialized existence and then setting the value has some time between it (nanoseconds??). Is it possible for two threads to overlap in this action???? I was have to say Yes to be cautious.

So, long story short, when using Application.cfm, I would recommend always doing the double-check locking. But, if you are using the Application.CFC with OnApplicationStart(), ColdFusion takes care of single-threading that on application start. Of course, if you put a manual reset in that, I would again, perform a double-check lock.


Mar 29, 2007 at 12:06 PM // reply »
2 Comments

Ben,

Why not perform the CFLOCK first and then do the check to make sure the app is not already initialized. If it is then bail on the lock otherwise complete the initialization action?

Ron


Mar 29, 2007 at 12:23 PM // reply »
7,488 Comments

@Ron,

If you do the CFLock out side of the CFIF statements that you force a portion of the Application.cfm to become single-threaded regardless of whether or not any app-initialization is going to take place. CFLock comes with slight overhead; for small sites, this might not matter, however, for a heavily trafficked site, this slight overhead on every single page request might start to slow things down.

Would people notice the slow down? Not sure, can't say. But, as a generally good practice, I would say you want to avoid locking whenever possible.


Jun 15, 2008 at 11:07 AM // reply »
2 Comments

Hi, slightly off topic but i noticed you use StructKeyExists alot instead of isdefined(), is there really much difference. Ie ,y friend told me not to use isdefined() anymore as it checks all the scopes and used more resources but is there really much difference?

Thanks pspboy


Jun 15, 2008 at 11:11 AM // reply »
7,488 Comments

@PspBoy,

IsDefined() works. But, personally, I think it is a "weak" statement. I like my ColdFusion code to be as assertive and descriptive as possible. If I know that a key should or should not exist in a given Struct, then I use StructKeyExists() because it is a very bold statement. There's something about IsDefined() that seems almost like a cop-out; it's like you're not even sure if it will be in a given struct or not.

It's a personal choice, mostly. But, I have heard that StructKeyExists() is faster.


Dec 1, 2009 at 4:19 PM // reply »
9 Comments

Thanks for writing this.

I needed a way to Clear all persistent Application variables this worked great.

<cfset StructClear( APPLICATION ) />

However can I have this in a non application.cfm file for it to work?

Dave


Jan 9, 2010 at 10:33 PM // reply »
7,488 Comments

@Dave,

You should be able to put that anywhere in your application (since APPLICATION is a globally accessible scope). However, you're probably gonna want to do it right before you initialize the Application scope, otherwise you might get "undefined" variable errors in the rest of the page request.


Post Comment  |  Ask Ben

Recent Blog Comments
sun
Mar 13, 2010 at 6:21 PM
Sending (SMS) Picture Messages With ColdFusion And CFMail
MY BAD! @tmomail.net IS correct ... but, ONLY from pic taken W/ a cell -- NOT as attachment in an email ... (took ~4 min. for it to arrive ... then would NOT DL to my cell) ... read »
sun
Mar 13, 2010 at 6:16 PM
Sending (SMS) Picture Messages With ColdFusion And CFMail
@tmomail.net is NOT correct! IS t-mobile addy ... but, ONLY for a txt msg! ... read »
Mar 12, 2010 at 8:24 PM
Creating UI Elements With Low-Coupling And Conditional Event Handling
@Ben, Yes, that's exactly what's happening. That's the approach YUI has taken with custom events, you subscribe the handler to the Event object itself. I really like the event system in YUI, it's ... read »
Mar 12, 2010 at 7:34 PM
FLV 404 Error On Windows 2003 Server
I spent a good couple of hours on this today. What a pain. On my old server, everything was fine. I migrated the site to a new server, and suddenly, all the files with audio didn't work. Just got ... read »
Mar 12, 2010 at 7:26 PM
Creating UI Elements With Low-Coupling And Conditional Event Handling
@Ryan, I finally got around to reading that YUI blog post you linked (it took me a fews months, but I did it). I wanted to ask you something (rather than on his only cause it is so old), but from w ... read »
Mar 12, 2010 at 2:00 PM
Tim Cracked The GMail - CFMailPart Puzzle!
@Mik Muller, Exactly what I was encountering... complaints of empty emails. I'm really surprised no one else has reported this anywhere. I realize text emails may seem old school but there are a lot ... read »
Mar 12, 2010 at 1:50 PM
Using jQuery's SlideUp() and SlideDown() Methods With Bottom-Positioned Elements
That's exactly the situation that came to my mind the other day. Saved my life there! xoxo ... read »
Mar 12, 2010 at 1:26 PM
Tim Cracked The GMail - CFMailPart Puzzle!
@Bruce Holm, Nice. This explains why some people reply with "email was empty" to me. Good work! ... read »