01: /*
02: Copyright 2004 Philip Jacob <phil@whirlycott.com>
03: Seth Fitzsimmons <seth@note.amherst.edu>
04:
05: Licensed under the Apache License, Version 2.0 (the "License");
06: you may not use this file except in compliance with the License.
07: 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: package com.whirlycott.cache.policy;
19:
20: import java.util.ArrayList;
21: import java.util.Collections;
22: import java.util.List;
23: import java.util.Map;
24: import java.util.Map.Entry;
25:
26: import org.apache.commons.logging.Log;
27: import org.apache.commons.logging.LogFactory;
28:
29: import com.whirlycott.cache.CacheMaintenancePolicy;
30: import com.whirlycott.cache.ManagedCache;
31: import com.whirlycott.cache.Messages;
32:
33: /**
34: * This policy removes cache items in the order in which they were added.
35: *
36: * @author Phil Jacob
37: */
38: public class FIFOMaintenancePolicy<K, V> implements
39: CacheMaintenancePolicy<K, V> {
40:
41: private static final Log log = LogFactory
42: .getLog(FIFOMaintenancePolicy.class);
43:
44: public void performMaintenance(ManagedCache<K, V> managedCache,
45: int maxSize) {
46: log
47: .debug(Messages
48: .getString("FIFOMaintenancePolicy.performing_fifo_maintenance"));
49:
50: log.debug(Messages.getCompoundString(
51: "CacheMaintenancePolicy.report_items", maxSize,
52: managedCache.size()));
53:
54: //Sort the entries in the cache.
55: final List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(
56: managedCache.entrySet());
57:
58: int currentSize = managedCache.size();
59:
60: if (maxSize < currentSize) {
61: log.debug(Messages.getCompoundString(
62: "CacheMaintenancePolicy.clearing_approximately",
63: currentSize - maxSize));
64: Collections.sort(entries, new AddedComparator());
65: final List<Map.Entry<K, V>> removeThese = entries.subList(
66: 0, currentSize - maxSize);
67: for (Entry<K, V> entry : removeThese) {
68: if (entry != null) {
69: //log.trace("Removing: " + entry.getKey());
70: managedCache.remove(entry.getKey());
71: }
72: }
73:
74: log.debug(Messages
75: .getString("FIFOMaintenancePolicy.new_size")
76: + managedCache.size());
77: }
78: }
79: }
|