“On demand computing”, as provided by Google Collections, turns a map into a computing map, which can be used as a basic cache for rare (but expensive) lookups.
Although the javadoc for this functionality is a good start, it can be opaque at times, especially for developers not entirely accustomed with the functional style of programming prevalent in the library.
The code below puts a computing map into context.
1. Computing map declaration.
//the 'usual' ConcurrentMap...
ConcurrentMap<Key, Value> computingMap =
// ... enhanced to support soft/weak keys/values, timed expiration and...
.new MapMaker()
//...on-demand computation...
.makeComputingMap(
//...passing into parameter an anonymous instance implementing the Function interface...
new Function<Key, Value>() {
//...where the function transforming a key into a value is defined so that....
public Value apply(Key key) {
//...it delegates to the a specialized, computationaly expensive function.
return createExpensiveValue(key);
}
2. Computationaly expensive function used to generate a value from a key.
Value createExpensiveValue(Key key){
Value computedValue = null;
/*transform the input key into the computedValue here
...
*/
return computedValue;
}
3. Retrieving values from the map
void retrieveValuesFromComputingMap() {
Key k = new Key(...);
//the map generates a value from the key and stores it.
Value v =computingMap.get(k);
//subsequent calls to retrieve the value associated with the key will fetch it directly from the map,
// skipping any other computation
}