1 8 package org.apache.avalon.excalibur.cache.store; 9 10 import java.util.ArrayList ; 11 import java.util.HashMap ; 12 import java.util.Map ; 13 import java.util.Set ; 14 15 18 public class FlipSpacesStore 19 extends AbstractCacheStore 20 { 21 24 private Map m_newCache = null; 25 26 30 private Map m_oldCache = null; 31 32 35 private int m_capacity; 36 37 42 public FlipSpacesStore( final int capacity ) 43 { 44 if ( capacity < 1 ) throw new IllegalArgumentException ( "Specified capacity must be at least 1" ); 45 46 m_capacity = capacity; 47 m_newCache = new HashMap ( m_capacity ); 48 m_oldCache = new HashMap ( m_capacity ); 49 } 50 51 61 public Object put( final Object key, final Object value ) 62 { 63 Object old = null; 64 get( key ); 65 old = m_newCache.put( key, value ); 66 if ( isFull() ) { 68 copySpaces(); 69 } 70 return old; 71 } 72 73 80 public Object remove( final Object key ) 81 { 82 Object cr = get( key ); 83 84 return m_newCache.remove( key ); 85 } 86 87 95 public Object get( final Object key ) 96 { 97 Object value = null; 98 if ( m_newCache.containsKey( key ) ) 99 { 100 value = m_newCache.get( key ); } 102 else 103 { 104 if ( m_oldCache.containsKey( key ) ) 105 { 106 value = m_oldCache.get( key ); if ( isFull() ) { 109 copySpaces(); 110 } 111 m_oldCache.remove( key ); m_newCache.put( key, value ); } 114 } 115 return value; 116 } 117 118 124 private void copySpaces() 125 { 126 m_oldCache.clear(); final Map temp = m_oldCache; m_oldCache = m_newCache; 129 m_newCache = temp; 130 } 131 132 136 public int size() 137 { 138 return m_newCache.size(); 139 } 140 141 145 public int capacity() 146 { 147 return m_capacity; 148 } 149 150 154 public boolean containsKey( final Object key ) 155 { 156 boolean rc = m_newCache.containsKey( key ); 157 if ( !rc ) 158 { 159 rc = m_oldCache.containsKey( key ); 160 } 161 return rc; 162 } 163 164 168 public Object [] keys() 169 { 170 final Set newKeys = m_newCache.keySet(); 171 final Set oldKeys = m_oldCache.keySet(); 172 final ArrayList keys = new ArrayList ( newKeys ); 173 keys.addAll( oldKeys ); 174 return keys.toArray(); 175 } 176 } | Popular Tags |