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 * @author Erik Brakkee
30 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
32 private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
35 * Callback invoked to compute an object if it was not found in the cache.
40 public static interface Computation<Key extends Serializable, Value extends Serializable> {
42 * Gets the object. Called when the object is not in the cache.
45 * Id of the object in the cache.
46 * @return Object, must be non-null.
48 Value getObject(Key aObjectKey);
54 private Cache<KeyType, ValueType> _cache;
57 * Key of the object in the cache.
59 private KeyType _objectKey;
62 * Computation used to obtain the object if it is not found in the cache.
64 private Computation<KeyType, ValueType> _computation;
67 * Constructs the cached object.
72 * Key of the object in the cache.
74 * Computation to get the object in case the object is not in the
77 public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
78 Computation<KeyType, ValueType> aComputation) {
80 _objectKey = aObjectKey;
81 _computation = aComputation;
85 * Gets the object. Since the object is cached, different calls to this
86 * method may return different objects.
90 public ValueType get() {
91 ValueType object = (ValueType) _cache.get(_objectKey); // the used
95 // synchronize the computation to make sure that the object is only
97 // once when multiple concurrent threads detect that the entry must
100 synchronized (this) {
101 object = (ValueType) _cache.get(_objectKey);
102 if (object == null) {
103 // No other thread did a recomputation so we must do this
105 LOGGER.debug("Refreshing cache for '" + _objectKey + "'");
106 object = _computation.getObject(_objectKey);
107 _cache.put(_objectKey, object);
115 * Invalidates the cache for the object so that it is recomputed the next
116 * time it is requested.
119 public void invalidate() {
120 _cache.remove(_objectKey);
128 public Cache getCache() {