Search This Blog

Monday 8 November 2010

Age Expiry Local Cache With Coherence

The local cache supports automatic expiration of entries based on the age of the value, as configured by the expiry-delay tag. The following example will show how to expire cache entries after the configured time as per expiry-delay, regardless of how many times the entry is updated, hence overriding the default behavior.

1. Create a java class as follows.
package support.au.coherence.examples;

import com.tangosol.net.cache.CacheLoader;
import com.tangosol.net.cache.LocalCache;
import com.tangosol.util.SafeHashMap;

public class AgeExpiryLocalCache extends LocalCache
{
  public AgeExpiryLocalCache()
  {
    super();
  }

  public AgeExpiryLocalCache(int cUnits)
  {
    super(cUnits);
  }

  public AgeExpiryLocalCache(int cUnits, int cExpiryMillis)
  {
    super(cUnits, cExpiryMillis);
  }

  public AgeExpiryLocalCache
  (int cUnits, int cExpiryMillis, CacheLoader loader)
  {
    super(cUnits, cExpiryMillis, loader);
  }

  protected SafeHashMap.Entry instantiateEntry()
  {
    return new Entry();
  }

  /**
   * Entry extension that will not reset expiry when entry
   * value is updated.
   */
  public class Entry extends LocalCache.Entry
  {
    public Entry()
    {
      super();
    }

    protected void scheduleExpiry()
    {
      // only set the expiry if it has not been set yet
      if (getExpiryMillis() > 0)
      {
        return;
      }
  
      super.scheduleExpiry();
    }
  }
}

2. Setup you cache config file to use this custom Local Cache as shown below.



 
   
     age-cache
     age-scheme
   
 
 
  
    age-scheme
      
        
           60s         
           
             support.au.coherence.examples.AgeExpiryLocalCache
           
        
      
      true
  
 


So in this example cache entries will expire 60 seconds after they are first inserted regardless of how often it is updated.

No comments: