2 * Copyright 2005-2010 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.cache;
18 import org.apache.log4j.Logger;
20 import java.io.Serializable;
23 * Represents a cached object. The object is either retrieved from the cache if
24 * the cache has it, or a call back is invoked to get the object (and put it in
27 * @author Erik Brakkee
30 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
31 private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
36 private Cache<KeyType, ValueType> cache;
39 * Key of the object in the cache.
41 private KeyType objectKey;
44 * Computation used to obtain the object if it is not found in the cache.
46 private Computation<KeyType, ValueType> computation;
49 * Constructs the cached object.
54 * Key of the object in the cache.
56 * Computation to get the object in case the object is not in the
59 public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
60 Computation<KeyType, ValueType> aComputation) {
62 objectKey = aObjectKey;
63 computation = aComputation;
67 * Gets the object. Since the object is cached, different calls to this
68 * method may return different objects.
72 public ValueType get() {
73 ValueType object = (ValueType) cache.get(objectKey); // the used
78 // synchronize the computation to make sure that the object is only
80 // once when multiple concurrent threads detect that the entry must
84 object = (ValueType) cache.get(objectKey);
87 // No other thread did a recomputation so we must do this
89 LOGGER.debug("Refreshing cache for '" + objectKey + "'");
90 object = computation.getObject(objectKey);
91 cache.put(objectKey, object);
100 * Invalidates the cache for the object so that it is recomputed the next
101 * time it is requested.
103 public void invalidate() {
104 cache.remove(objectKey);
112 public Cache getCache() {
117 * Callback invoked to compute an object if it was not found in the cache.
122 public static interface Computation<Key extends Serializable, Value extends Serializable> {
124 * Gets the object. Called when the object is not in the cache.
127 * Id of the object in the cache.
129 * @return Object, must be non-null.
131 Value getObject(Key aObjectKey);