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 the cache
25 * has it, or a call back is invoked to get the object (and put it in the cache).
27 public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
29 private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
32 * Callback invoked to compute an object if it was not found in the cache.
33 * @param <T> Type of the object
35 public static interface Computation<Key extends Serializable, Value extends Serializable> {
37 * Gets the object. Called when the object is not in the cache.
38 * @param aObjectKey Id of the object in the cache.
39 * @return Object, must be non-null.
41 Value getObject(Key aObjectKey);
47 private Cache<KeyType, ValueType> _cache;
50 * Key of the object in the cache.
52 private KeyType _objectKey;
55 * Computation used to obtain the object if it is not found in the cache.
57 private Computation<KeyType, ValueType> _computation;
60 * Constructs the cached object.
61 * @param aCache Cache to use.
62 * @param aObjectKey Key of the object in the cache.
63 * @param aComputation Computation to get the object in case the object is not in the cache.
65 public CachedObject(Cache<KeyType,ValueType> aCache, KeyType aObjectKey, Computation<KeyType,ValueType> aComputation) {
67 _objectKey = aObjectKey;
68 _computation = aComputation;
72 * Gets the object. Since the object is cached, different calls to this method may return
76 public ValueType get() {
77 ValueType object = (ValueType)_cache.get(_objectKey); // the used cache is thread safe.
78 if ( object == null ) {
79 // synchronize the computation to make sure that the object is only computed
80 // once when multiple concurrent threads detect that the entry must be
83 object = (ValueType)_cache.get(_objectKey);
84 if ( object == null ) {
85 // No other thread did a recomputation so we must do this now.
86 LOGGER.debug("Refreshing cache for '" + _objectKey + "'");
87 object = _computation.getObject(_objectKey);
88 _cache.put(_objectKey, object);
96 * Invalidates the cache for the object so that it is recomputed the next
97 * time it is requested.
100 public void invalidate() {
101 _cache.remove(_objectKey);
108 public Cache getCache() {