KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jsmtpd > tools > cache > SimpleCache


1 /*
2  *
3  * Jsmtpd, Java SMTP daemon
4  * Copyright (C) 2005 Jean-Francois POUX, jf.poux@laposte.net
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */

21 package org.jsmtpd.tools.cache;
22
23 import java.util.ArrayList JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Map JavaDoc;
28
29 /**
30  * Simple RAM Cache.
31  * @author jean-francois POUX
32  *
33  * @param <Key>
34  * @param <Value>
35  */

36 public class SimpleCache<Key,Value> implements ICache<Key,Value> {
37     private Map JavaDoc<Key,Value> cachedValues = Collections.synchronizedMap(new HashMap JavaDoc<Key,Value>());
38     private List JavaDoc<Key> keys = Collections.synchronizedList(new ArrayList JavaDoc<Key>());
39     private int cacheSize = 200;
40     
41     public SimpleCache(int cacheSize) {
42         this.cacheSize=cacheSize;
43     }
44     
45     public synchronized Value get(Key k) {
46         if (!keys.contains(k))
47             return null;
48         keys.remove(k);
49         keys.add(0,k); // put key in front (latest use)
50
return cachedValues.get(k);
51     }
52     
53     public synchronized void cache(Key key, Value value) {
54         if (keys.size()>cacheSize) {
55             int removeSize = Math.round(cacheSize / 10);
56             for (int c=0;c<removeSize;c++) {
57                 Key cKey = keys.get(keys.size());
58                 keys.remove(cKey);
59                 cachedValues.remove(cKey);
60             }
61         }
62         keys.add(0,key);
63         cachedValues.put(key,value);
64         
65     }
66     
67     public synchronized void clear() {
68         keys.clear();
69         cachedValues.clear();
70         
71     }
72     
73     public synchronized void destroy(Key k) {
74         keys.remove(k);
75         cachedValues.remove(k);
76     }
77
78     
79     public void setCacheSize(int cacheSize) {
80         this.cacheSize = cacheSize;
81     }
82    
83 }
84
Popular Tags