01: /*
02: *
03: * Jsmtpd, Java SMTP daemon
04: * Copyright (C) 2005 Jean-Francois POUX, jf.poux@laposte.net
05: *
06: * This program is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU General Public License
08: * as published by the Free Software Foundation; either version 2
09: * 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;
24: import java.util.Collections;
25: import java.util.HashMap;
26: import java.util.List;
27: import java.util.Map;
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<Key, Value> cachedValues = Collections
38: .synchronizedMap(new HashMap<Key, Value>());
39: private List<Key> keys = Collections
40: .synchronizedList(new ArrayList<Key>());
41: private int cacheSize = 200;
42:
43: public SimpleCache(int cacheSize) {
44: this .cacheSize = cacheSize;
45: }
46:
47: public synchronized Value get(Key k) {
48: if (!keys.contains(k))
49: return null;
50: keys.remove(k);
51: keys.add(0, k); // put key in front (latest use)
52: return cachedValues.get(k);
53: }
54:
55: public synchronized void cache(Key key, Value value) {
56: if (keys.size() > cacheSize) {
57: int removeSize = Math.round(cacheSize / 10);
58: for (int c = 0; c < removeSize; c++) {
59: Key cKey = keys.get(keys.size());
60: keys.remove(cKey);
61: cachedValues.remove(cKey);
62: }
63: }
64: keys.add(0, key);
65: cachedValues.put(key, value);
66:
67: }
68:
69: public synchronized void clear() {
70: keys.clear();
71: cachedValues.clear();
72:
73: }
74:
75: public synchronized void destroy(Key k) {
76: keys.remove(k);
77: cachedValues.remove(k);
78: }
79:
80: public void setCacheSize(int cacheSize) {
81: this.cacheSize = cacheSize;
82: }
83:
84: }
|