01: /**
02: * Copyright 2003-2007 Luck Consulting Pty Ltd
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not 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.
15: */package net.sf.ehcache.store;
16:
17: import net.sf.ehcache.CacheException;
18: import net.sf.ehcache.Ehcache;
19: import net.sf.ehcache.Element;
20: import org.apache.commons.logging.Log;
21: import org.apache.commons.logging.LogFactory;
22:
23: import java.io.Serializable;
24: import java.util.Iterator;
25: import java.util.LinkedHashMap;
26: import java.util.Set;
27:
28: /**
29: * First-In-First-Out (FIFO) implementation of MemoryStore.
30: *
31: * @author <a href="mailto:ssuravarapu@users.sourceforge.net">Surya Suravarapu</a>
32: * @version $Id: FifoMemoryStore.java 519 2007-07-27 07:11:45Z gregluck $
33: */
34: public class FifoMemoryStore extends MemoryStore {
35: private static final Log LOG = LogFactory
36: .getLog(FifoMemoryStore.class.getName());
37:
38: /**
39: * Constructor for the FifoMemoryStore object.
40: * <p/>
41: * First tries to use {@link java.util.LinkedHashMap}. If not found uses
42: * Jakarta Commons collections.
43: */
44: public FifoMemoryStore(Ehcache cache, Store diskStore) {
45: super (cache, diskStore);
46: map = new LinkedHashMap();
47: }
48:
49: /**
50: * Allow specialised actions over adding the element to the map
51: *
52: * @param element
53: */
54: protected final void doPut(Element element) throws CacheException {
55: if (isFull()) {
56: removeFirstElement();
57: }
58: }
59:
60: /**
61: * Returns the first eligible element that can be taken out of the cache
62: * based on the FIFO policy
63: */
64: Element getFirstElement() {
65: if (map.size() == 0) {
66: return null;
67: }
68:
69: Element element = null;
70: Serializable key;
71:
72: Set keySet = map.keySet();
73: Iterator itr = keySet.iterator();
74: // The first element is the candidate to remove
75: if (itr.hasNext()) {
76: key = (Serializable) itr.next();
77: element = (Element) map.get(key);
78: }
79:
80: return element;
81: }
82:
83: /**
84: * Remove the first element that is eligible to removed from the store
85: * based on the FIFO policy
86: */
87: private void removeFirstElement() throws CacheException {
88: Element element = getFirstElement();
89:
90: if (element.isExpired()) {
91: remove(element.getObjectKey());
92: notifyExpiry(element);
93: return;
94: }
95: remove(element.getObjectKey());
96: evict(element);
97: }
98: }
|