KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > cache > policy > TimeMapLRUPolicy


1 /*
2  * Copyright (C) The Apache Software Foundation. All rights reserved.
3  *
4  * This software is published under the terms of the Apache Software License
5  * version 1.1, a copy of which has been included with this distribution in
6  * the LICENSE.txt file.
7  */

8 package org.apache.avalon.excalibur.cache.policy;
9
10 import java.util.HashMap JavaDoc;
11 import java.util.TreeMap JavaDoc;
12 import org.apache.avalon.excalibur.cache.ReplacementPolicy;
13
14 /**
15  * TimeMapLRU(Least Recently Used) replacement policy.
16  * Use a TreeMap with logical time to perform LRU <code>selectVictim</code> operations.
17  * On large cache this implementation should be really faster (since it uses a
18  * log(n) treemap plus an hashmap) than the current LRU implem that is working with a List.
19  *
20  * @author <a HREF="alag@users.sourceforge.net">Alexis Agahi</a>
21  */

22 public class TimeMapLRUPolicy
23     implements ReplacementPolicy
24 {
25
26     protected TreeMap JavaDoc m_timeToKeyMap;
27     protected HashMap JavaDoc m_keyToTimeMap;
28
29     private long m_time;
30     private Object JavaDoc m_lock;
31
32     public TimeMapLRUPolicy()
33     {
34         m_timeToKeyMap = new TreeMap JavaDoc();
35         m_keyToTimeMap = new HashMap JavaDoc();
36         m_time = 0;
37         m_lock = new Object JavaDoc();
38     }
39
40     public void hit( final Object JavaDoc key )
41     {
42         remove( key );
43         add( key );
44     }
45
46     public void add( final Object JavaDoc key )
47     {
48         Long JavaDoc time = getTime();
49         m_timeToKeyMap.put( time, key );
50         m_keyToTimeMap.put( key, time );
51     }
52
53     public void remove( final Object JavaDoc key )
54     {
55         Long JavaDoc time = (Long JavaDoc)m_keyToTimeMap.remove( key );
56         m_timeToKeyMap.remove( time );
57     }
58
59     public Object JavaDoc selectVictim()
60     {
61         Object JavaDoc time = m_timeToKeyMap.firstKey();
62         Object JavaDoc key = m_timeToKeyMap.get( time );
63         return key;
64     }
65
66     private Long JavaDoc getTime()
67     {
68         synchronized ( m_lock )
69         {
70             return new Long JavaDoc( m_time++ );
71         }
72     }
73 }
74
Popular Tags