01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18:
19: /* $Id: CacheMap.java 531479 2007-04-23 14:21:35Z andreas $ */
20:
21: package org.apache.lenya.util;
22:
23: import java.util.Date;
24: import java.util.HashMap;
25: import java.util.SortedMap;
26: import java.util.TreeMap;
27:
28: import org.apache.avalon.framework.logger.LogEnabled;
29: import org.apache.avalon.framework.logger.Logger;
30:
31: /**
32: * A map with a maximum capacity. When the map is full, the oldest entry is removed.
33: */
34: public class CacheMap extends HashMap implements LogEnabled {
35:
36: /**
37: *
38: */
39: private static final long serialVersionUID = 1L;
40:
41: /**
42: * Ctor.
43: * @param _capacity The maximum number of entries.
44: * @param logger The logger.
45: */
46: public CacheMap(int _capacity, Logger logger) {
47: enableLogging(logger);
48: assert _capacity > -1;
49: this .capacity = _capacity;
50: }
51:
52: private int capacity;
53: private SortedMap timeToKey = new TreeMap();
54: private Logger logger;
55:
56: /**
57: * @see java.util.Map#put(Object, Object)
58: */
59: public Object put(Object key, Object value) {
60:
61: if (size() == this .capacity) {
62: Object oldestKey = this .timeToKey.get(this .timeToKey
63: .firstKey());
64: remove(oldestKey);
65: if (getLogger().isDebugEnabled()) {
66: getLogger().debug("Clearing cache");
67: }
68: }
69: this .timeToKey.put(new Date(), key);
70: return super .put(key, value);
71: }
72:
73: /**
74: * @see java.util.Map#get(java.lang.Object)
75: */
76: public Object get(Object key) {
77: Object result = super .get(key);
78: if (getLogger().isDebugEnabled()) {
79: if (result != null) {
80: getLogger().debug(
81: "Using cached object for key [" + key + "]");
82: } else {
83: getLogger().debug(
84: "No cached object for key [" + key + "]");
85: }
86: }
87: return result;
88: }
89:
90: protected Logger getLogger() {
91: return this .logger;
92: }
93:
94: public void enableLogging(Logger logger) {
95: this.logger = logger;
96: }
97:
98: }
|