Code Samples

Thread local caches should only by accessed where the correct context (thread) exists. For instance, it is not recommended to set up a thread local cache in static block of code as that thread might not be the same as the thread using the cache later.

Figure 1. Setting up and using a thread local cache
public void myMethod() {
  ...
  Cache<String, String> threadCache = CacheManager.
           getThreadLocalCacheGroup().getCache("mycache");
  String value = threadCache.get("key");
  if(value == null) {
    // perform expensive operation to calculate value - this
    // processing only happens once for each thread
    ...
    // and store the result
    threadCache.put("key", "value");
  }
  ...
}