2 * Copyright 2005 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;
24 * Represents a cached object. The object is either retrieved from the
25 * cache if the cache has it, or a call back is invoked to get the object (and
26 * put it in the cache).
28 * @author Erik Brakkee
30 * @param <KeyType> DOCUMENT ME!
31 * @param <ValueType> DOCUMENT ME!
33 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
37 private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
42 private Cache<KeyType, ValueType> cache;
45 * Key of the object in the cache.
47 private KeyType objectKey;
50 * Computation used to obtain the object if it is not found in the
53 private Computation<KeyType, ValueType> computation;
56 * Constructs the cached object.
61 * Key of the object in the cache.
63 * Computation to get the object in case the object is not in the
66 public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
67 Computation<KeyType, ValueType> aComputation) {
69 objectKey = aObjectKey;
70 computation = aComputation;
74 * Gets the object. Since the object is cached, different calls to
75 * this method may return different objects.
79 public ValueType get() {
80 ValueType object = (ValueType) cache.get(objectKey); // the used
85 // synchronize the computation to make sure that the object is only
87 // once when multiple concurrent threads detect that the entry must
91 object = (ValueType) cache.get(objectKey);
94 // No other thread did a recomputation so we must do this
96 LOGGER.debug("Refreshing cache for '" + objectKey + "'");
97 object = computation.getObject(objectKey);
98 cache.put(objectKey, object);
107 * Invalidates the cache for the object so that it is recomputed
108 * the next time it is requested.
110 public void invalidate() {
111 cache.remove(objectKey);
119 public Cache getCache() {
124 * Callback invoked to compute an object if it was not found in the cache.
129 public static interface Computation<Key extends Serializable, Value extends Serializable> {
131 * Gets the object. Called when the object is not in the
134 * @param aObjectKey Id of the object in the cache.
136 * @return Object, must be non-null.
138 Value getObject(Key aObjectKey);