UTILS-16
[utils] / support / general / src / main / java / org / wamblee / cache / CachedObject.java
index bdabd51795a92787893ed87c862827a8eb754586..70baf67ca9c298c6de19ea0a2967c6a6b184e876 100644 (file)
@@ -1,12 +1,12 @@
 /*
- * Copyright 2005 the original author or authors.
- *
+ * Copyright 2005-2010 the original author or authors.
+ * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- *
+ * 
  *      http://www.apache.org/licenses/LICENSE-2.0
- *
+ * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  */
 package org.wamblee.cache;
 
-import org.apache.log4j.Logger;
-
 import java.io.Serializable;
-
+import java.util.logging.Level;
+import java.util.logging.Logger;
 
 /**
- * Represents a cached object. The object is either retrieved from the
- * cache if the cache has it, or a call back is invoked to get the object (and
- * put it in the cache).
+ * Represents a cached object identified by the key it has in a certain
+ * {@link Cache}. The object is either retrieved from the cache if the cache has
+ * it, or a call back is invoked to get the object (and put it in the cache).
  *
  * @author Erik Brakkee
- *
- * @param <KeyType> DOCUMENT ME!
- * @param <ValueType> DOCUMENT ME!
  */
 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
-    /**
-     * DOCUMENT ME!
-     */
-    private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
+    private static final Logger LOGGER = Logger.getLogger(CachedObject.class.getName());
 
     /**
      * Cache to use.
@@ -47,65 +40,93 @@ public class CachedObject<KeyType extends Serializable, ValueType extends Serial
     private KeyType objectKey;
 
     /**
-     * Computation used to obtain the object if it is not found in the
-     * cache.
+     * Last known value. We only use this to return the last known value in case recomputation of the value fails.
+     */
+    private ValueType value;
+
+    /**
+     * Are we now computing the value or not?
+     */
+    private boolean computing;
+
+    /**
+     * Computation used to obtain the object if it is not found in the cache.
      */
     private Computation<KeyType, ValueType> computation;
 
-/**
+    /**
      * Constructs the cached object.
      *
-     * @param aCache
-     *            Cache to use.
-     * @param aObjectKey
-     *            Key of the object in the cache.
-     * @param aComputation
-     *            Computation to get the object in case the object is not in the
-     *            cache.
+     * @param aCache       Cache to use.
+     * @param aObjectKey   Key of the object in the cache.
+     * @param aComputation Computation to get the object in case the object is not in the
+     *                     cache.
      */
     public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
-        Computation<KeyType, ValueType> aComputation) {
-        cache           = aCache;
-        objectKey       = aObjectKey;
-        computation     = aComputation;
+            Computation<KeyType, ValueType> aComputation) {
+        cache = aCache;
+        objectKey = aObjectKey;
+        computation = aComputation;
     }
 
     /**
-     * Gets the object. Since the object is cached, different calls to
-     * this method may return different objects.
+     * Gets the object. Since the object is cached, different calls to this
+     * method may return different objects.
+     * <p/>
+     * If the object is expired from the cache it is recomputed using the
+     * callback. In case the callback throws an exception the last known value
+     * is used. In case an exception is thrown, the problem is also logged. In
+     * case a recomputation is already being done by another thread, the last
+     * known value is immediately returned.
      *
      * @return Object.
      */
     public ValueType get() {
-        ValueType object = (ValueType) cache.get(objectKey); // the used
-                                                             // cache is
-                                                             // thread safe.
-
-        if (object == null) {
-            // synchronize the computation to make sure that the object is only
-            // computed
-            // once when multiple concurrent threads detect that the entry must
-            // be
-            // recomputed.
-            synchronized (this) {
-                object = (ValueType) cache.get(objectKey);
+        synchronized (this) {
+            if (computing) {
+                // always return old value while computing.
+                return value;
+            }
 
-                if (object == null) {
-                    // No other thread did a recomputation so we must do this
-                    // now.
-                    LOGGER.debug("Refreshing cache for '" + objectKey + "'");
-                    object = computation.getObject(objectKey);
-                    cache.put(objectKey, object);
-                }
+            ValueType cachedValue = cache.get(objectKey);
+            if (cachedValue == null) {
+                // expired
+                computing = true;
+            } else {
+                // Two different instances of cached object might share the same cache and so it can occur
+                // that the value in one of the instances it out of date.
+                value = cachedValue;
+                return value;
             }
         }
+        try {
 
-        return object;
+            // we only get here if we are computing
+            // do the computation without holding the lock.
+            LOGGER.fine("Refreshing cache for '" + objectKey + "'");
+            ValueType object = computation.getObject(objectKey);
+            cache.put(objectKey, object);
+
+            synchronized (this) {
+                value = object;
+            }
+        }
+        catch (Exception e) {
+            LOGGER.log(Level.INFO, "Recomputation of cached item failed for key '" + objectKey +
+                    "'", e);
+        } finally {
+            synchronized (this) {
+                computing = false;
+            }
+        }
+        synchronized (this) {
+            return value;
+        }
     }
 
     /**
-     * Invalidates the cache for the object so that it is recomputed
-     * the next time it is requested.
+     * Invalidates the cache for the object so that it is recomputed the next
+     * time it is requested.
      */
     public void invalidate() {
         cache.remove(objectKey);
@@ -120,21 +141,20 @@ public class CachedObject<KeyType extends Serializable, ValueType extends Serial
         return cache;
     }
 
-/**
+    /**
      * Callback invoked to compute an object if it was not found in the cache.
      *
-     * @param <T>
-     *            Type of the object
+     * @param <T> Type of the object
      */
     public static interface Computation<Key extends Serializable, Value extends Serializable> {
         /**
-         * Gets the object. Called when the object is not in the
-         * cache.
+         * Gets the object. Called when the object is not in the cache. In case
+         * computation fails, an exception should be thrown to ensure that the
+         * last known value will be used.
          *
          * @param aObjectKey Id of the object in the cache.
-         *
          * @return Object, must be non-null.
          */
-        Value getObject(Key aObjectKey);
+        Value getObject(Key aObjectKey) throws Exception;
     }
 }