1 28 29 package com.caucho.util; 30 31 38 public class FlatCache<K,V> { 39 private Object []_keys; 40 private V []_values; 41 42 private int _capacity; 44 private int _mask; 45 46 private static Object NULL = new Object (); 47 48 public FlatCache(int initialCapacity) 49 { 50 for (_capacity = 32; _capacity < 2 * initialCapacity; _capacity *= 2) { 51 } 52 53 _keys = new Object [_capacity]; 54 _values = (V []) new Object [_capacity]; 55 56 _mask = _capacity - 1; 57 } 58 59 62 public synchronized void clear() 63 { 64 for (int i = 0; i < _capacity; i++) { 65 if (_values[i] instanceof CacheListener) 66 ((CacheListener) _values[i]).removeEvent(); 67 68 _keys[i] = null; 69 _values[i] = null; 70 } 71 } 72 73 79 public Object get(K key) 80 { 81 Object okey = key; 82 if (okey == null) 83 okey = NULL; 84 85 int hash = okey.hashCode() & _mask; 86 87 Object testKey = _keys[hash]; 88 89 if (testKey != null && testKey.equals(okey) && testKey == _keys[hash]) 90 return _values[hash]; 91 else 92 return null; 93 } 94 95 104 public synchronized V put(K key, V value) 105 { 106 Object okey = key; 107 if (okey == null) 108 okey = NULL; 109 110 int hash = okey.hashCode() & _mask; 111 112 V old = _values[hash]; 113 114 _keys[hash] = null; 115 _values[hash] = value; 116 _keys[hash] = okey; 117 118 if (old instanceof CacheListener) 119 ((CacheListener) old).removeEvent(); 120 121 return old; 122 } 123 124 131 public V remove(K key) 132 { 133 return put(key, null); 134 } 135 } 136 | Popular Tags |