A Switching NamedCache Implementation

I decided to write this blog after the technique had been mentioned on the Oracle Coherence forum a few times as a solution to various requirements but without any real detail or without covering some of the questions that this technique poses. The technique in question is basically where you have two caches on the server side and the client needs to use one or the other to get data depending on a flag in another cache. One example of the requirement would be this forum post

Personally I think that this solution is not always suitable but if you want to go down this route then it can be done in such a way that the client code is kept as simple as possible – in fact using the techniques I am going to write about here the client does not know they are using anything other than a normal NamedCache.

So, to be clear, lets state our requirement: We have two caches on the server side – lets call them CacheA and CacheB and we have a replicated cache that contains a flag to tell us whether to use CacheA or CacheB for data, we will call this the FlagCache. The flag cache will have an entry in it with a well known key that we use to get the flag, we’ll call this the FlagKey. As we are only flipping between two caches we can make the flag value a boolean although you could expand this to have more than two underlying caches if you had some requirement that needed it.

To use this technique every time we need to use the cache we need to know which cache to go to so the steps are…

  1.     Boolean flag = flagCache.get(flagKey);
  2.     NamedCache cacheToUse;
  3.     if (flag) {
  4.         cacheToUse = cacheA;
  5.     } else {
  6.         cacheToUse = cacheB;
  7.     }
  8.     cacheToUse. ... do something ...
    Boolean flag = flagCache.get(flagKey);
    NamedCache cacheToUse;
    if (flag) {
        cacheToUse = cacheA;
    } else {
        cacheToUse = cacheB;
    }
    cacheToUse. ... do something ...

OK, not too much code but do we really want to do that all over our client code – no we do not. We could encapsulate the code above in some sort of utility method that returns the cache to use, but again we need to call this method everywhere before we do anything. A better technique is for the client to not have to even know that it is using more than one underlying cache and this is how we do it.

Wrap The Underlying Caches

First we write a wrapper class that implements NamedCache. This wrapper encapsulates both CacheA and CacheB and the code to check which cache to call. When any of its methods are called it then forward the method call to the correct cache using the code we used above. Sounds simple, and it is, but there are a few gotchas we will cover later.

Here is the wrapper class

  1. import com.tangosol.net.CacheService;
  2. import com.tangosol.net.NamedCache;
  3. import com.tangosol.util.Filter;
  4. import com.tangosol.util.MapListener;
  5. import com.tangosol.util.ValueExtractor;
  6.  
  7. import java.util.Collection;
  8. import java.util.Comparator;
  9. import java.util.Map;
  10. import java.util.Set;
  11.  
  12. /**
  13.  * @author Jonathan Knight
  14.  */
  15. public class SwitchingNamedCache implements NamedCache
  16. {
  17.  
  18.     private NamedCache cacheA;
  19.     private NamedCache cacheB;
  20.     private NamedCache flagCache;
  21.     private Object flagKey;
  22.  
  23.     public SwitchingNamedCache(NamedCache cacheA, NamedCache cacheB, NamedCache flagCache, Object flagKey)
  24.     {
  25.         this.cacheA = cacheA;
  26.         this.cacheB = cacheB;
  27.         this.flagCache = flagCache;
  28.         this.flagKey = flagKey;
  29.     }
  30.  
  31.     public NamedCache getCurrentCache()
  32.     {
  33.         Boolean flag = (Boolean) flagCache.get(flagKey);
  34.         NamedCache currentCache;
  35.         if (flag == null || flag) {
  36.             currentCache = cacheA;
  37.         } else {
  38.             currentCache = cacheB;
  39.         }
  40.         return currentCache;
  41.     }
  42.  
  43.     public Set entrySet()
  44.     {
  45.         return getCurrentCache().entrySet();
  46.     }
  47.  
  48.     public Set keySet()
  49.     {
  50.         return getCurrentCache().keySet();
  51.     }
  52.  
  53.     public Collection values()
  54.     {
  55.         return getCurrentCache().values();
  56.     }
  57.  
  58.     public boolean containsKey(Object oKey)
  59.     {
  60.         return getCurrentCache().containsKey(oKey);
  61.     }
  62.  
  63.     public boolean isEmpty()
  64.     {
  65.         return getCurrentCache().isEmpty();
  66.     }
  67.  
  68.     public int size()
  69.     {
  70.         return getCurrentCache().size();
  71.     }
  72.  
  73.     public boolean containsValue(Object oValue)
  74.     {
  75.         return getCurrentCache().containsValue(oValue);
  76.     }
  77.  
  78.     public Object get(Object oKey)
  79.     {
  80.         return getCurrentCache().get(oKey);
  81.     }
  82.  
  83.     public void addMapListener(MapListener listener)
  84.     {
  85.         getCurrentCache().addMapListener(listener);
  86.     }
  87.  
  88.     public void removeMapListener(MapListener listener)
  89.     {
  90.         getCurrentCache().removeMapListener(listener);
  91.     }
  92.  
  93.     public void addMapListener(MapListener listener, Object oKey, boolean fLite)
  94.     {
  95.         getCurrentCache().addMapListener(listener, oKey, fLite);
  96.     }
  97.  
  98.     public void removeMapListener(MapListener listener, Object oKey)
  99.     {
  100.         getCurrentCache().removeMapListener(listener, oKey);
  101.     }
  102.  
  103.     public void addMapListener(MapListener listener, Filter filter, boolean fLite)
  104.     {
  105.         getCurrentCache().addMapListener(listener, filter, fLite);
  106.     }
  107.  
  108.     public void removeMapListener(MapListener listener, Filter filter)
  109.     {
  110.         getCurrentCache().removeMapListener(listener, filter);
  111.     }
  112.  
  113.     public String toString()
  114.     {
  115.         return "SwitchingNamedCache currentCache=" + getCurrentCache().toString();
  116.     }
  117.  
  118.     public boolean lock(Object oKey, long cWait)
  119.     {
  120.         return getCurrentCache().lock(oKey, cWait);
  121.     }
  122.  
  123.     public boolean lock(Object oKey)
  124.     {
  125.         return getCurrentCache().lock(oKey);
  126.     }
  127.  
  128.     public boolean unlock(Object oKey)
  129.     {
  130.         return getCurrentCache().unlock(oKey);
  131.     }
  132.  
  133.     public void clear()
  134.     {
  135.         getCurrentCache().clear();
  136.     }
  137.  
  138.     public Object put(Object oKey, Object oValue)
  139.     {
  140.         return getCurrentCache().put(oKey, oValue);
  141.     }
  142.  
  143.     public void putAll(Map map)
  144.     {
  145.         getCurrentCache().putAll(map);
  146.     }
  147.  
  148.     public Object remove(Object oKey)
  149.     {
  150.         return getCurrentCache().remove(oKey);
  151.     }
  152.  
  153.     public String getCacheName()
  154.     {
  155.         return getCurrentCache().getCacheName();
  156.     }
  157.  
  158.     public CacheService getCacheService()
  159.     {
  160.         return getCurrentCache().getCacheService();
  161.     }
  162.  
  163.     public boolean isActive()
  164.     {
  165.         return getCurrentCache().isActive();
  166.     }
  167.  
  168.     public void release()
  169.     {
  170.         getCurrentCache().release();
  171.     }
  172.  
  173.     public void destroy()
  174.     {
  175.         getCurrentCache().destroy();
  176.     }
  177.  
  178.     public Map getAll(Collection colKeys)
  179.     {
  180.         return getCurrentCache().getAll(colKeys);
  181.     }
  182.  
  183.     public Object put(Object oKey, Object oValue, long cMillis)
  184.     {
  185.         return getCurrentCache().put(oKey, oValue, cMillis);
  186.     }
  187.  
  188.     public Set keySet(Filter filter)
  189.     {
  190.         return getCurrentCache().keySet(filter);
  191.     }
  192.  
  193.     public Set entrySet(Filter filter)
  194.     {
  195.         return getCurrentCache().entrySet(filter);
  196.     }
  197.  
  198.     public Set entrySet(Filter filter, Comparator comparator)
  199.     {
  200.         return getCurrentCache().entrySet(filter, comparator);
  201.     }
  202.  
  203.     public void addIndex(ValueExtractor extractor, boolean fOrdered, Comparator comparator)
  204.     {
  205.         cacheA.addIndex(extractor, fOrdered, comparator);
  206.         cacheB.addIndex(extractor, fOrdered, comparator);
  207.     }
  208.  
  209.     public void removeIndex(ValueExtractor extractor)
  210.     {
  211.         cacheA.removeIndex(extractor);
  212.         cacheB.removeIndex(extractor);
  213.     }
  214.  
  215.     public Object invoke(Object oKey, EntryProcessor agent)
  216.     {
  217.         return getCurrentCache().invoke(oKey, agent);
  218.     }
  219.  
  220.     public Map invokeAll(Collection collKeys, EntryProcessor agent)
  221.     {
  222.         return getCurrentCache().invokeAll(collKeys, agent);
  223.     }
  224.  
  225.     public Map invokeAll(Filter filter, EntryProcessor agent)
  226.     {
  227.         return getCurrentCache().invokeAll(filter, agent);
  228.     }
  229.  
  230.     public Object aggregate(Collection collKeys, EntryAggregator agent)
  231.     {
  232.         return getCurrentCache().aggregate(collKeys, agent);
  233.     }
  234.  
  235.     public Object aggregate(Filter filter, EntryAggregator agent)
  236.     {
  237.         return getCurrentCache().aggregate(filter, agent);
  238.     }
  239. }
import com.tangosol.net.CacheService;
import com.tangosol.net.NamedCache;
import com.tangosol.util.Filter;
import com.tangosol.util.MapListener;
import com.tangosol.util.ValueExtractor;

import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;

/**
 * @author Jonathan Knight
 */
public class SwitchingNamedCache implements NamedCache
{

    private NamedCache cacheA;
    private NamedCache cacheB;
    private NamedCache flagCache;
    private Object flagKey;

    public SwitchingNamedCache(NamedCache cacheA, NamedCache cacheB, NamedCache flagCache, Object flagKey)
    {
        this.cacheA = cacheA;
        this.cacheB = cacheB;
        this.flagCache = flagCache;
        this.flagKey = flagKey;
    }

    public NamedCache getCurrentCache()
    {
        Boolean flag = (Boolean) flagCache.get(flagKey);
        NamedCache currentCache;
        if (flag == null || flag) {
            currentCache = cacheA;
        } else {
            currentCache = cacheB;
        }
        return currentCache;
    }

    public Set entrySet()
    {
        return getCurrentCache().entrySet();
    }

    public Set keySet()
    {
        return getCurrentCache().keySet();
    }

    public Collection values()
    {
        return getCurrentCache().values();
    }

    public boolean containsKey(Object oKey)
    {
        return getCurrentCache().containsKey(oKey);
    }

    public boolean isEmpty()
    {
        return getCurrentCache().isEmpty();
    }

    public int size()
    {
        return getCurrentCache().size();
    }

    public boolean containsValue(Object oValue)
    {
        return getCurrentCache().containsValue(oValue);
    }

    public Object get(Object oKey)
    {
        return getCurrentCache().get(oKey);
    }

    public void addMapListener(MapListener listener)
    {
        getCurrentCache().addMapListener(listener);
    }

    public void removeMapListener(MapListener listener)
    {
        getCurrentCache().removeMapListener(listener);
    }

    public void addMapListener(MapListener listener, Object oKey, boolean fLite)
    {
        getCurrentCache().addMapListener(listener, oKey, fLite);
    }

    public void removeMapListener(MapListener listener, Object oKey)
    {
        getCurrentCache().removeMapListener(listener, oKey);
    }

    public void addMapListener(MapListener listener, Filter filter, boolean fLite)
    {
        getCurrentCache().addMapListener(listener, filter, fLite);
    }

    public void removeMapListener(MapListener listener, Filter filter)
    {
        getCurrentCache().removeMapListener(listener, filter);
    }

    public String toString()
    {
        return "SwitchingNamedCache currentCache=" + getCurrentCache().toString();
    }

    public boolean lock(Object oKey, long cWait)
    {
        return getCurrentCache().lock(oKey, cWait);
    }

    public boolean lock(Object oKey)
    {
        return getCurrentCache().lock(oKey);
    }

    public boolean unlock(Object oKey)
    {
        return getCurrentCache().unlock(oKey);
    }

    public void clear()
    {
        getCurrentCache().clear();
    }

    public Object put(Object oKey, Object oValue)
    {
        return getCurrentCache().put(oKey, oValue);
    }

    public void putAll(Map map)
    {
        getCurrentCache().putAll(map);
    }

    public Object remove(Object oKey)
    {
        return getCurrentCache().remove(oKey);
    }

    public String getCacheName()
    {
        return getCurrentCache().getCacheName();
    }

    public CacheService getCacheService()
    {
        return getCurrentCache().getCacheService();
    }

    public boolean isActive()
    {
        return getCurrentCache().isActive();
    }

    public void release()
    {
        getCurrentCache().release();
    }

    public void destroy()
    {
        getCurrentCache().destroy();
    }

    public Map getAll(Collection colKeys)
    {
        return getCurrentCache().getAll(colKeys);
    }

    public Object put(Object oKey, Object oValue, long cMillis)
    {
        return getCurrentCache().put(oKey, oValue, cMillis);
    }

    public Set keySet(Filter filter)
    {
        return getCurrentCache().keySet(filter);
    }

    public Set entrySet(Filter filter)
    {
        return getCurrentCache().entrySet(filter);
    }

    public Set entrySet(Filter filter, Comparator comparator)
    {
        return getCurrentCache().entrySet(filter, comparator);
    }

    public void addIndex(ValueExtractor extractor, boolean fOrdered, Comparator comparator)
    {
        cacheA.addIndex(extractor, fOrdered, comparator);
        cacheB.addIndex(extractor, fOrdered, comparator);
    }

    public void removeIndex(ValueExtractor extractor)
    {
        cacheA.removeIndex(extractor);
        cacheB.removeIndex(extractor);
    }

    public Object invoke(Object oKey, EntryProcessor agent)
    {
        return getCurrentCache().invoke(oKey, agent);
    }

    public Map invokeAll(Collection collKeys, EntryProcessor agent)
    {
        return getCurrentCache().invokeAll(collKeys, agent);
    }

    public Map invokeAll(Filter filter, EntryProcessor agent)
    {
        return getCurrentCache().invokeAll(filter, agent);
    }

    public Object aggregate(Collection collKeys, EntryAggregator agent)
    {
        return getCurrentCache().aggregate(collKeys, agent);
    }

    public Object aggregate(Filter filter, EntryAggregator agent)
    {
        return getCurrentCache().aggregate(filter, agent);
    }
}

Using the Wrapper Class

So how does our client code use the SwitchingNamedCache? Well, the client could construct an instance every time like this.

  1. NamedCache cacheA = CacheFactory.getCache("cache-a");
  2. NamedCache cacheB = CacheFactory.getCache("cache-b");
  3. NamedCache flagCache = CacheFactory.getCache("flag-cache");
  4. NamedCache cache = new SwitchingNamedCache(cacheA, cacheB, flagCache, "cache-a-b-flag");
  5.  
  6. ... use cache as normal ...
NamedCache cacheA = CacheFactory.getCache("cache-a");
NamedCache cacheB = CacheFactory.getCache("cache-b");
NamedCache flagCache = CacheFactory.getCache("flag-cache");
NamedCache cache = new SwitchingNamedCache(cacheA, cacheB, flagCache, "cache-a-b-flag");

... use cache as normal ...

Again not too hard but far better if the client didn’t need to do this – as I said we do not want the client to know about the fact the data is coming from multiple caches.

To do this we can use some cache configuration to do the work for us. The magic that allows us to do this, and something that is probably not used much by many people is the macros that can be used in the cache configuration file described in the Coherence Docs here In particular we are going to use the {cache-ref} macro.

Here is an example cache configuration file that uses our SwitchingNamedCache.
In our example say we have a cache of exchange rates and at a certain time we want to switch from one set of rates to another so we do this with two caches, A-exchange-rates and B-exchange-rates but the client only ever needs to ask for the exchange-rates cache.

  1. <cache-config
  2.     xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">
  5.  
  6.   <defaults>
  7.     <serializer>pof</serializer>
  8.   </defaults>
  9.  
  10.   <caching-scheme-mapping>
  11.     <cache-mapping>
  12.       <cache-name>exchange-rates</cache-name>
  13.       <scheme-name>switching-scheme</scheme-name>
  14.       <init-params>
  15.         <init-param>
  16.               <param-name>cache-A</param-name>
  17.           <param-value>A-exchange-rates</param-value>
  18.         </init-param>
  19.         <init-param>
  20.           <param-name>cache-B</param-name>
  21.           <param-value>B-exchange-rates</param-value>
  22.         </init-param>
  23.       </init-params>
  24.     </cache-mapping>
  25.  
  26.     <cache-mapping>
  27.       <cache-name>A-*</cache-name>
  28.       <scheme-name>distributed-scheme</scheme-name>
  29.     </cache-mapping>
  30.  
  31.     <cache-mapping>
  32.       <cache-name>B-*</cache-name>
  33.       <scheme-name>distributed-scheme</scheme-name>
  34.     </cache-mapping>
  35.  
  36.     <cache-mapping>
  37.       <cache-name>flag-cache</cache-name>
  38.       <scheme-name>replicated-scheme</scheme-name>
  39.     </cache-mapping>
  40.  
  41.   </caching-scheme-mapping>
  42.  
  43.   <caching-schemes>
  44.  
  45.     <distributed-scheme>
  46.       <scheme-name>distributed-scheme</scheme-name>
  47.       <service-name>DistributedService</service-name>
  48.       <thread-count>10</thread-count>
  49.       <backing-map-scheme>
  50.         <local-scheme>
  51.           <unit-calculator>BINARY</unit-calculator>
  52.         </local-scheme>
  53.       </backing-map-scheme>
  54.       <autostart>true</autostart>
  55.     </distributed-scheme>
  56.  
  57.     <replicated-scheme>
  58.       <scheme-name>replicated-scheme</scheme-name>
  59.       <service-name>ReplicatedCache</service-name>
  60.       <backing-map-scheme>
  61.         <local-scheme/>
  62.       </backing-map-scheme>
  63.       <autostart>true</autostart>
  64.     </replicated-scheme>
  65.  
  66.     <class-scheme>
  67.       <scheme-name>switching-scheme</scheme-name>
  68.       <class-name>com.thegridman.coherence.cache.SwitchingNamedCache</class-name>
  69.       <init-params>
  70.         <init-param>
  71.           <param-type>{cache-ref}</param-type>
  72.           <param-value>{cache-A}</param-value>
  73.         </init-param>
  74.         <init-param>
  75.           <param-type>{cache-ref}</param-type>
  76.           <param-value>{cache-B}</param-value>
  77.         </init-param>
  78.         <init-param>
  79.           <param-type>{cache-ref}</param-type>
  80.           <param-value>flag-cache</param-value>
  81.         </init-param>
  82.         <init-param>
  83.           <param-type>String</param-type>
  84.           <param-value>flag-key</param-value>
  85.         </init-param>
  86.       </init-params>
  87.     </class-scheme>
  88.  
  89.   </caching-schemes>
  90.  
  91. </cache-config>
<cache-config
    xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">

  <defaults>
    <serializer>pof</serializer>
  </defaults>

  <caching-scheme-mapping>
    <cache-mapping>
      <cache-name>exchange-rates</cache-name>
      <scheme-name>switching-scheme</scheme-name>
      <init-params>
        <init-param>
              <param-name>cache-A</param-name>
          <param-value>A-exchange-rates</param-value>
        </init-param>
        <init-param>
          <param-name>cache-B</param-name>
          <param-value>B-exchange-rates</param-value>
        </init-param>
      </init-params>
    </cache-mapping>

    <cache-mapping>
      <cache-name>A-*</cache-name>
      <scheme-name>distributed-scheme</scheme-name>
    </cache-mapping>

    <cache-mapping>
      <cache-name>B-*</cache-name>
      <scheme-name>distributed-scheme</scheme-name>
    </cache-mapping>

    <cache-mapping>
      <cache-name>flag-cache</cache-name>
      <scheme-name>replicated-scheme</scheme-name>
    </cache-mapping>

  </caching-scheme-mapping>

  <caching-schemes>

    <distributed-scheme>
      <scheme-name>distributed-scheme</scheme-name>
      <service-name>DistributedService</service-name>
      <thread-count>10</thread-count>
      <backing-map-scheme>
        <local-scheme>
          <unit-calculator>BINARY</unit-calculator>
        </local-scheme>
      </backing-map-scheme>
      <autostart>true</autostart>
    </distributed-scheme>

    <replicated-scheme>
      <scheme-name>replicated-scheme</scheme-name>
      <service-name>ReplicatedCache</service-name>
      <backing-map-scheme>
        <local-scheme/>
      </backing-map-scheme>
      <autostart>true</autostart>
    </replicated-scheme>

    <class-scheme>
      <scheme-name>switching-scheme</scheme-name>
      <class-name>com.thegridman.coherence.cache.SwitchingNamedCache</class-name>
      <init-params>
        <init-param>
          <param-type>{cache-ref}</param-type>
          <param-value>{cache-A}</param-value>
        </init-param>
        <init-param>
          <param-type>{cache-ref}</param-type>
          <param-value>{cache-B}</param-value>
        </init-param>
        <init-param>
          <param-type>{cache-ref}</param-type>
          <param-value>flag-cache</param-value>
        </init-param>
        <init-param>
          <param-type>String</param-type>
          <param-value>flag-key</param-value>
        </init-param>
      </init-params>
    </class-scheme>

  </caching-schemes>

</cache-config>

There are probably a few slightly different ways we could have done the configuration above but we’ll go through what we have done here – and you’ll have to excuse the bad formatting where the init-param tags are but for some reason I could not get them to use the correct number of spaces, either WordPress or the formatting plugin is messing it up.

First we have a simple distributed-scheme which both of our “A” and “B” exchange rate caches map to. We also have a replicated scheme that holds the flag that indicates whether we should use the “A” or “B” cache.

You can see we have defined a mapping for the exchange-rates cache to a class-scheme, which is our SwitchingNamedCache class. The class takes four parameters, the “A” and “B” caches, the cache to check for the flag, and they key of the entry that holds the flag. This is where we use the {cache-ref} macro that covnverts the string value into the actual NamedCache reference that will be passed to the SwitchingNamedCache constructor.

Now all the client or application code ever needs to do is access the exchange-rates cache as it would any other cache. Any application code that uses exchange-rates has no idea that it is reading from the “A” or “B” cache, which is exactly what we want.

so if we did this in our code somewhere…

  1. // Populate the A cache with some rates
  2. NamedCache cacheA = CacheFactory.getCache("A-exchange-rates");
  3. cacheA.put("GBP-USD", 1.53d);
  4.  
  5. // Set the flag to make the A cache the one to be used
  6. NamedCache flagCache = CacheFactory.getCache("flag-cache");
  7. flagCache.put("flag-key", true);
// Populate the A cache with some rates
NamedCache cacheA = CacheFactory.getCache("A-exchange-rates");
cacheA.put("GBP-USD", 1.53d);

// Set the flag to make the A cache the one to be used
NamedCache flagCache = CacheFactory.getCache("flag-cache");
flagCache.put("flag-key", true);

…we have now initialised the “A” cache with a rate and set the flag to true so application code will use the “A” cache.

In our client we do this to get a rate just like normal

  1. NamedCache exchangeRates = CacheFactory.getCache("exchange-rates");
  2. double rate = exchangeRates.get("GBP-USD");
NamedCache exchangeRates = CacheFactory.getCache("exchange-rates");
double rate = exchangeRates.get("GBP-USD");

The client will get the rate of 1.53 Simple code, no messing about with flags etc.

Now we want to switch to the “B” cache so somewhere we do this…

  1. // Make sure the B cache has some rates
  2. NamedCache cacheB = CacheFactory.getCache("B-exchange-rates");
  3. cacheB.put("GBP-USD", 1.50d);
  4.  
  5. // Flip the flag so the the B cache is used
  6. NamedCache flagCache = CacheFactory.getCache("flag-cache");
  7. flagCache.put("flag-key", false);
// Make sure the B cache has some rates
NamedCache cacheB = CacheFactory.getCache("B-exchange-rates");
cacheB.put("GBP-USD", 1.50d);

// Flip the flag so the the B cache is used
NamedCache flagCache = CacheFactory.getCache("flag-cache");
flagCache.put("flag-key", false);

In our client we still only do this to get a rate just like normal

  1. NamedCache exchangeRates = CacheFactory.getCache("exchange-rates");
  2. double rate = exchangeRates.get("GBP-USD");
NamedCache exchangeRates = CacheFactory.getCache("exchange-rates");
double rate = exchangeRates.get("GBP-USD");

This time the client will get the rate of 1.50

So, there we go, the client end is very simple with no messing about.

Caveats

Now, there are some things that will not work very well with this setup, or any sort of cache switching setup, which we will cover now.

Indexes

Adding and removing indexes should really be done to both the “A” and “B” cache regardless of which is in use. An application may add an index when it starts in which case when the swithc is made the index will not be there and so queries will suddenly be slower and less efficient. The code shown for the SwitchingNamedCache actually passes the addIndex and removeIndex calls to both the “A” and “B” caches.

Map Listeners

Adding Map listeners is not really supported as an application could add a listener to the cache and when the switch occurs the listener will then be on the wrong cache. We could do something clever in the SwitchingNamedCache to keep track of listeners and when the switch occurs move them to the correct cache but the move cannot easily be done in an atomic way that guarantees you do not get messages you do not want or make sure you do not miss messages you want.

Continuous Query Cache

As listeners are not really supported neither are CQCs as these rely on MapListeners to do their job. In the example above you would not be able to create a CQC that wrapped the exchange-rates cache, or rather you could create a CQC but it would not work very well after the switch.

Near Caching

Similar to MapListeners and CQCs, near caches also rely on events to work properly. In this case though you can still use near caches, but you need to apply them to the “A” and “B” caches rather than to the SwitchingNamedCache. To do this in the example above we would create a near-scheme in the cache-schemes section of the configuration like this

  1.     <near-scheme>
  2.       <scheme-name>near-scheme</scheme-name>
  3.       <front-scheme>
  4.           <local-scheme/>
  5.       </front-scheme>
  6.       <back-scheme>
  7.         <distributed-scheme>
  8.           <scheme-ref>distributed-scheme</scheme-ref>
  9.         </distributed-scheme>
  10.       </back-scheme>
  11.     </near-scheme>
    <near-scheme>
      <scheme-name>near-scheme</scheme-name>
      <front-scheme>
          <local-scheme/>
      </front-scheme>
      <back-scheme>
        <distributed-scheme>
          <scheme-ref>distributed-scheme</scheme-ref>
        </distributed-scheme>
      </back-scheme>
    </near-scheme>

We would then change the mapping of the A-* and B-* caches to map to the near-scheme instead of the distributed-scheme.

  1.     <cache-mapping>
  2.       <cache-name>A-*</cache-name>
  3.       <scheme-name>near-scheme</scheme-name>
  4.     </cache-mapping>
  5.  
  6.     <cache-mapping>
  7.       <cache-name>B-*</cache-name>
  8.       <scheme-name>near-scheme</scheme-name>
  9.     </cache-mapping>
    <cache-mapping>
      <cache-name>A-*</cache-name>
      <scheme-name>near-scheme</scheme-name>
    </cache-mapping>

    <cache-mapping>
      <cache-name>B-*</cache-name>
      <scheme-name>near-scheme</scheme-name>
    </cache-mapping>

The configuration above would be used in storage disabled clients as you would not normally have near caches on your storage enabled nodes.

Timing

The one other caveat is to do with timing of calls to the wrapped cache by the application code.
Consider the following example…

  1. NamedCache cache = Cachefactory.getCache"exchange-rates");
  2. Filter filter = ... create some sort of Filter ...
  3. Set<Map.Entry> entries = cache.entrySet(filter);
  4. for (Map.Entry entry : entries) {
  5.    ... do some processing ...
  6. }
NamedCache cache = Cachefactory.getCache"exchange-rates");
Filter filter = ... create some sort of Filter ...
Set<Map.Entry> entries = cache.entrySet(filter);
for (Map.Entry entry : entries) {
   ... do some processing ...
}

Now, the code above is pretty simple but… what happens if some other code executes that flips the cache flag while this code is executing – say between lines 3 and 4 or while the for loop is being iterated over. For a number of cases this might not be a problem but it depends on what the code inside the for loop is doing. If the code is relying on having the correct data for a point in time then that is no longer the case. This problem though is no different to a similar application that uses say a DB rather than Coherence and the table it is executing against gets updated during processing, but it is at least something to be aware of.

Efficiency

Rather than the getCurrentCache method having to call the replicated cache every time it might be more efficient to add a listener to the flag cache that gets notified when the switch occurs. This could then set a field to the value of the cache to use rather than having to do the checke every time.

Conclusions

So there we have it, not too complicated if you really need to do this sort of thing. Personally, in all my years of using Coherence I have not needed it but as I said I have seen it mentioned on the Coherence forum as a possible solution to requirements. The {cache-ref} macro is really very useful for this sort of thing and we have made the client side very simple. The main advantage that gives is that anyone writing application code does not need to worry about having to put in a lot of boiler plate code to work out which cache to use, so that means less bugs where developers forget to do it. Application code can obtain a reference to the cache and pass it around the code without having to worry that the cache reference might become stale if the cache to use flag gets flipped at some point.

 

2 Responses to Switching Cache Pattern in Oracle Coherence

  1. Is it legal to create our own implementation of the NamedCache? Does it not constitute as a derived work? Hmm… Just curious.

    • jk says:

      Of course it is legal, it is just an implementation of an interface. If this was illegal so would writing your own implementations of Filter, EntryProcessor, Aggregator etc…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">