KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > util > CacheMap


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */

17
18 /* $Id: CacheMap.java 42598 2004-03-01 16:18:28Z gregor $ */
19
20 package org.apache.lenya.util;
21
22 import java.util.Date JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.SortedMap JavaDoc;
25 import java.util.TreeMap JavaDoc;
26
27 import org.apache.log4j.Category;
28
29 /**
30  * A map with a maximum capacity. When the map is full, the oldest entry is removed.
31  */

32 public class CacheMap extends HashMap JavaDoc {
33     
34     private static final Category log = Category.getInstance(CacheMap.class);
35     
36     /**
37      * Ctor.
38      * @param capacity The maximum number of entries.
39      */

40     public CacheMap(int capacity) {
41         assert capacity > -1;
42         this.capacity = capacity;
43     }
44     
45     private int capacity;
46     private SortedMap JavaDoc timeToKey = new TreeMap JavaDoc();
47     
48     /**
49      * @see java.util.Map#put(Object, Object)
50      */

51     public Object JavaDoc put(Object JavaDoc key, Object JavaDoc value) {
52         
53         if (size() == capacity) {
54             Object JavaDoc oldestKey = timeToKey.get(timeToKey.firstKey());
55             remove(oldestKey);
56             if (log.isDebugEnabled()) {
57                 log.debug("Clearing cache");
58             }
59         }
60         timeToKey.put(new Date JavaDoc(), key);
61         return super.put(key, value);
62     }
63     
64     
65     
66     /**
67      * @see java.util.Map#get(java.lang.Object)
68      */

69     public Object JavaDoc get(Object JavaDoc key) {
70         Object JavaDoc result = super.get(key);
71         if (log.isDebugEnabled()) {
72             if (result != null) {
73                 log.debug("Using cached object for key [" + key + "]");
74             }
75             else {
76                 log.debug("No cached object for key [" + key + "]");
77             }
78         }
79         return result;
80     }
81
82 }
83
Popular Tags