Google Collections’ computing map

“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.

//a ConcurrentMap... 
ConcurrentMap<Key, Value> computingMap =   
// enhanced to support soft/weak keys/values, timed expiration and...
        .new MapMaker()  
//on-demand computation...
//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

Leave a Reply

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

You are commenting using your 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