function getExpensiveResult(){
synchronized(applicationScope) {
if(isCacheInvalid("example_key", 600)) {
result = // do expensive computation of something, like iterating through a view or so
applicationScope.put("example_key", result);
}
}
return applicationScope.get("example_key");
}
/**
A generic caching mechanism for each key will check to see if it is 'n' seconds
since it was last updated. Use for things that change relatively infrequently
*/
function isCacheInvalid(key, cacheInterval){
var currentTime = new Date().getTime();
if (!applicationScope.containsKey(key + "_time")){
applicationScope.put(key + "_time", currentTime);
return true;
}
var diffInSecs = Math.ceil((currentTime - applicationScope.get(key + "_time")) / 1000);
if (diffInSecs < cacheInterval) {
return false;
} else {
applicationScope.put(key + "_time", currentTime);
return true;
}
}