Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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