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.
17 package org.wamblee.cache;
19 import java.io.Serializable;
21 import org.apache.log4j.Logger;
24 * Represents a cached object. The object is either retrieved from the cache if
25 * the cache has it, or a call back is invoked to get the object (and put it in
28 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
30 private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
33 * Callback invoked to compute an object if it was not found in the cache.
38 public static interface Computation<Key extends Serializable, Value extends Serializable> {
40 * Gets the object. Called when the object is not in the cache.
43 * Id of the object in the cache.
44 * @return Object, must be non-null.
46 Value getObject(Key aObjectKey);
52 private Cache<KeyType, ValueType> _cache;
55 * Key of the object in the cache.
57 private KeyType _objectKey;
60 * Computation used to obtain the object if it is not found in the cache.
62 private Computation<KeyType, ValueType> _computation;
65 * Constructs the cached object.
70 * Key of the object in the cache.
72 * Computation to get the object in case the object is not in the
75 public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
76 Computation<KeyType, ValueType> aComputation) {
78 _objectKey = aObjectKey;
79 _computation = aComputation;
83 * Gets the object. Since the object is cached, different calls to this
84 * method may return different objects.
88 public ValueType get() {
89 ValueType object = (ValueType) _cache.get(_objectKey); // the used
93 // synchronize the computation to make sure that the object is only
95 // once when multiple concurrent threads detect that the entry must
99 object = (ValueType) _cache.get(_objectKey);
100 if (object == null) {
101 // No other thread did a recomputation so we must do this
103 LOGGER.debug("Refreshing cache for '" + _objectKey + "'");
104 object = _computation.getObject(_objectKey);
105 _cache.put(_objectKey, object);
113 * Invalidates the cache for the object so that it is recomputed the next
114 * time it is requested.
117 public void invalidate() {
118 _cache.remove(_objectKey);
126 public Cache getCache() {