ShotokuRenewableCacheExample

An example of usage of Shotoku Renewable Cache

 

First, you need to define a data source:

 

package org.jboss.shotoku.cache.test;

import org.jboss.shotoku.cache.CacheItemDataSource;
import org.jboss.shotoku.cache.ValueChange;

import java.io.*;

public class TestDataSource implements CacheItemDataSource<String, MyConfiguration> {
     private MyConfiguration getConfiguration(File f) {
          FileReader fr = new FileReader(f);
          // Read and parse data from the file ...
          return parsedConfigurationData;
     }

     public Integer init(String key) {
          return getConfiguration(new File(key));
     }

     public ValueChange<MyConfiguration> update(String key, MyConfiguration currentObject) {
          // Checking if the file, from which data is read, was modified.
          File f = new File(key);
          if (currentObject.getSourceFileLastModification() != f.lastModification()) {
               return ValueChange.changeTo(getConfiguration(f));
          } else {
               return ValueChange.noChange();
          }
     }
     
     public String getInfo() {
          return "A test data source.";
     }
}

 

Here, the keys of objects in the cache are Strings, and values are of type MyConfiguration. The init function returns the initial value for a given key (when a value for that key is first demanded), and the update function either parses the configuration again (if the source file was modified since the last update) or makes no change to the value held in the cache.

 

Having defined a data source, here is how you can use it in your application (service, web application, etc, here using an imaginary service):

     private CacheItemUser<String, MyConfiguration> myTestCacheItem;

     public initMyService() {
          (...)
          myTestCacheItem = CacheItem.create(new TestDataSource())
          (...)
     }

     public serviceRequest(RequestData request) {
          (...)
          String filename = request.getParameter("filename");
          MyConfiguration conf = myTestCacheItem.get(filename);
          (...)
     }

and that's it. First invocation of myTestCacheItem.get(filename) initializes the value for the given key, and any subsequent ones just read the value from the cache (of course, the get function is thread-safe).

 

You can specify the FQN of an associated tree node and the interval between updates of the cache item as parameters of the create function. You can also change the interval later. If the FQN is not specified, it will be auto-generated.