70baf67ca9c298c6de19ea0a2967c6a6b184e876
[utils] / support / general / src / main / java / org / wamblee / cache / CachedObject.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.cache;
17
18 import java.io.Serializable;
19 import java.util.logging.Level;
20 import java.util.logging.Logger;
21
22 /**
23  * Represents a cached object identified by the key it has in a certain
24  * {@link Cache}. The object is either retrieved from the cache if the cache has
25  * it, or a call back is invoked to get the object (and put it in the cache).
26  *
27  * @author Erik Brakkee
28  */
29 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
30     private static final Logger LOGGER = Logger.getLogger(CachedObject.class.getName());
31
32     /**
33      * Cache to use.
34      */
35     private Cache<KeyType, ValueType> cache;
36
37     /**
38      * Key of the object in the cache.
39      */
40     private KeyType objectKey;
41
42     /**
43      * Last known value. We only use this to return the last known value in case recomputation of the value fails.
44      */
45     private ValueType value;
46
47     /**
48      * Are we now computing the value or not?
49      */
50     private boolean computing;
51
52     /**
53      * Computation used to obtain the object if it is not found in the cache.
54      */
55     private Computation<KeyType, ValueType> computation;
56
57     /**
58      * Constructs the cached object.
59      *
60      * @param aCache       Cache to use.
61      * @param aObjectKey   Key of the object in the cache.
62      * @param aComputation Computation to get the object in case the object is not in the
63      *                     cache.
64      */
65     public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
66             Computation<KeyType, ValueType> aComputation) {
67         cache = aCache;
68         objectKey = aObjectKey;
69         computation = aComputation;
70     }
71
72     /**
73      * Gets the object. Since the object is cached, different calls to this
74      * method may return different objects.
75      * <p/>
76      * If the object is expired from the cache it is recomputed using the
77      * callback. In case the callback throws an exception the last known value
78      * is used. In case an exception is thrown, the problem is also logged. In
79      * case a recomputation is already being done by another thread, the last
80      * known value is immediately returned.
81      *
82      * @return Object.
83      */
84     public ValueType get() {
85         synchronized (this) {
86             if (computing) {
87                 // always return old value while computing.
88                 return value;
89             }
90
91             ValueType cachedValue = cache.get(objectKey);
92             if (cachedValue == null) {
93                 // expired
94                 computing = true;
95             } else {
96                 // Two different instances of cached object might share the same cache and so it can occur
97                 // that the value in one of the instances it out of date.
98                 value = cachedValue;
99                 return value;
100             }
101         }
102         try {
103
104             // we only get here if we are computing
105             // do the computation without holding the lock.
106             LOGGER.fine("Refreshing cache for '" + objectKey + "'");
107             ValueType object = computation.getObject(objectKey);
108             cache.put(objectKey, object);
109
110             synchronized (this) {
111                 value = object;
112             }
113         }
114         catch (Exception e) {
115             LOGGER.log(Level.INFO, "Recomputation of cached item failed for key '" + objectKey +
116                     "'", e);
117         } finally {
118             synchronized (this) {
119                 computing = false;
120             }
121         }
122         synchronized (this) {
123             return value;
124         }
125     }
126
127     /**
128      * Invalidates the cache for the object so that it is recomputed the next
129      * time it is requested.
130      */
131     public void invalidate() {
132         cache.remove(objectKey);
133     }
134
135     /**
136      * Gets the cache.
137      *
138      * @return Cache.
139      */
140     public Cache getCache() {
141         return cache;
142     }
143
144     /**
145      * Callback invoked to compute an object if it was not found in the cache.
146      *
147      * @param <T> Type of the object
148      */
149     public static interface Computation<Key extends Serializable, Value extends Serializable> {
150         /**
151          * Gets the object. Called when the object is not in the cache. In case
152          * computation fails, an exception should be thrown to ensure that the
153          * last known value will be used.
154          *
155          * @param aObjectKey Id of the object in the cache.
156          * @return Object, must be non-null.
157          */
158         Value getObject(Key aObjectKey) throws Exception;
159     }
160 }