Drawing Blanks

Premature Optimization is a Prerequisite for Success

Caching pattern

leave a comment »

The following pattern is wrong:

(pseudocode)
if GetDataFromCache() is Nothing then
   CacheData(GetDataFromDatabase());
return GetDataFromCache();

The data could be removed from cache between the two operators and the code will return Nothing. This will likely cause hard to debug NullReferenceExceptions.

This is not improbable in web apps. The cache manager uses heuristics based on many factors. When the app is under high load, items may be removed from cache right after they are inserted. The correct pattern is

data = GetDataFromCache();
if data is Nothing then
{
   data = GetDataFromDatabase()
   CacheData(data);
}
return data;

Note that in this case the object is always referenced and even if it gets removed from cache we don’t lose it

Advertisements

Written by bbzippo

12/14/2009 at 5:07 pm

Posted in programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: