01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. The ASF licenses this file to You
04: * under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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. For additional information regarding
15: * copyright in this work, please see the NOTICE file in the top level
16: * directory of this distribution.
17: */
18:
19: package org.apache.roller.util.cache;
20:
21: import org.apache.commons.logging.Log;
22: import org.apache.commons.logging.LogFactory;
23:
24: /**
25: * An LRU cache where entries expire after a given timeout period.
26: */
27: public class ExpiringLRUCacheImpl extends LRUCacheImpl {
28:
29: private static Log log = LogFactory
30: .getLog(ExpiringLRUCacheImpl.class);
31:
32: private long timeout = 0;
33:
34: protected ExpiringLRUCacheImpl(String id) {
35:
36: super (id);
37: this .timeout = 60 * 60 * 1000;
38: }
39:
40: protected ExpiringLRUCacheImpl(String id, int maxsize, long timeout) {
41:
42: super (id, maxsize);
43:
44: // timeout is specified in seconds; only positive values allowed
45: if (timeout > 0) {
46: this .timeout = timeout * 1000;
47: }
48: }
49:
50: /**
51: * Store an entry in the cache.
52: *
53: * We wrap the cached object in our ExpiringCacheEntry object so that we
54: * can track when the entry has expired.
55: */
56: public synchronized void put(String key, Object value) {
57:
58: ExpiringCacheEntry entry = new ExpiringCacheEntry(value,
59: this .timeout);
60: super .put(key, entry);
61: }
62:
63: /**
64: * Retrieve an entry from the cache.
65: *
66: * This LRU cache supports timeouts, so if the cached object has expired
67: * then we return null, just as if the entry wasn't found.
68: */
69: public Object get(String key) {
70:
71: Object value = null;
72: ExpiringCacheEntry entry = null;
73:
74: synchronized (this ) {
75: entry = (ExpiringCacheEntry) super .get(key);
76: }
77:
78: if (entry != null) {
79:
80: value = entry.getValue();
81:
82: // if the value is null then that means this entry expired
83: if (value == null) {
84: log.debug("EXPIRED [" + key + "]");
85: hits--;
86: super.remove(key);
87: }
88: }
89:
90: return value;
91: }
92:
93: }
|