Skip to content

Instantly share code, notes, and snippets.

@MrDOS
Created June 5, 2015 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrDOS/e0d65a61bd72a75df404 to your computer and use it in GitHub Desktop.
Save MrDOS/e0d65a61bd72a75df404 to your computer and use it in GitHub Desktop.
An example of how to cache a value in a static field.
public class StaticFieldCacheExample
{
/* Define a static field to hold the value. */
private static String cachedValue = null;
public static String getCachedValue()
{
/* If the value has been previously calculated, return it immediately
* instead of performing an expensive calculation. */
if (StaticFieldCacheExample.cachedValue != null)
return StaticFieldCacheExample.cachedValue;
/* Perform the requisite steps to calculate the value to be cached. */
String calculatedValue = 'whatever';
/* Before returning the newly-calculated value, update the cache. Now
* the cache value is non-null, we'll bypass the expensive calculations
* next time this method is called. */
StaticFieldCacheExample.cachedValue = calculatedValue;
return calculatedValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment