Remove the eldest entries until the total of remaining entries is at or below the requested size. @param maxSize the maximum size of the cache before returning. May be -1 to evict even 0-sized elements.
(int maxSize)
| 162 | * to evict even 0-sized elements. |
| 163 | */ |
| 164 | public void trimToSize(int maxSize) { |
| 165 | while (true) { |
| 166 | K key; |
| 167 | V value; |
| 168 | synchronized (this) { |
| 169 | if (size < 0 || (map.isEmpty() && size != 0)) { |
| 170 | throw new IllegalStateException(getClass().getName() |
| 171 | + ".sizeOf() is reporting inconsistent results!"); |
| 172 | } |
| 173 | |
| 174 | if (size <= maxSize || map.isEmpty()) { |
| 175 | break; |
| 176 | } |
| 177 | |
| 178 | Map.Entry<K, V> toEvict = map.entrySet().iterator().next(); |
| 179 | key = toEvict.getKey(); |
| 180 | value = toEvict.getValue(); |
| 181 | map.remove(key); |
| 182 | size -= safeSizeOf(key, value); |
| 183 | evictionCount++; |
| 184 | } |
| 185 | |
| 186 | entryRemoved(true, key, value, null); |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /** |
| 191 | * Removes the entry for {@code key} if it exists. |
no test coverage detected