| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.dev.cache; |
| 7 |
|
| 8 |
import java.util.AbstractMap; |
| 9 |
import java.util.ArrayList; |
| 10 |
import java.util.HashMap; |
| 11 |
import java.util.HashSet; |
| 12 |
import java.util.List; |
| 13 |
import java.util.Map; |
| 14 |
import java.util.Set; |
| 15 |
|
| 16 |
/** |
| 17 |
* A scan resistant cache. It is meant to cache objects that are relatively |
| 18 |
* costly to acquire, for example file content. |
| 19 |
* <p> |
| 20 |
* This implementation is multi-threading safe and supports concurrent access. |
| 21 |
* Null keys or null values are not allowed. The map fill factor is at most 75%. |
| 22 |
* <p> |
| 23 |
* Each entry is assigned a distinct memory size, and the cache will try to use |
| 24 |
* at most the specified amount of memory. The memory unit is not relevant, |
| 25 |
* however it is suggested to use bytes as the unit. |
| 26 |
* <p> |
| 27 |
* This class implements an approximation of the LIRS replacement algorithm |
| 28 |
* invented by Xiaodong Zhang and Song Jiang as described in |
| 29 |
* https://web.cse.ohio-state.edu/~zhang.574/lirs-sigmetrics-02.html with a few |
| 30 |
* smaller changes: An additional queue for non-resident entries is used, to |
| 31 |
* prevent unbound memory usage. The maximum size of this queue is at most the |
| 32 |
* size of the rest of the stack. About 6.25% of the mapped entries are cold. |
| 33 |
* <p> |
| 34 |
* Internally, the cache is split into a number of segments, and each segment is |
| 35 |
* an individual LIRS cache. |
| 36 |
* <p> |
| 37 |
* Accessed entries are only moved to the top of the stack if at least a number |
| 38 |
* of other entries have been moved to the front (8 per segment by default). |
| 39 |
* Write access and moving entries to the top of the stack is synchronized per |
| 40 |
* segment. |
| 41 |
* |
| 42 |
* @author Thomas Mueller |
| 43 |
* @param <K> the key type |
| 44 |
* @param <V> the value type |
| 45 |
*/ |
| 46 |
public class CacheLIRS<K, V> extends AbstractMap<K, V> { |
| 47 |
|
| 48 |
/** |
| 49 |
* The maximum memory this cache should use. |
| 50 |
*/ |
| 51 |
private long maxMemory; |
| 52 |
|
| 53 |
private final Segment<K, V>[] segments; |
| 54 |
|
| 55 |
private final int segmentCount; |
| 56 |
private final int segmentShift; |
| 57 |
private final int segmentMask; |
| 58 |
private final int stackMoveDistance; |
| 59 |
|
| 60 |
|
| 61 |
/** |
| 62 |
* Create a new cache with the given number of entries, and the default |
| 63 |
* settings (16 segments, and stack move distance of 8. |
| 64 |
* |
| 65 |
* @param maxMemory the maximum memory to use (1 or larger) |
| 66 |
*/ |
| 67 |
public CacheLIRS(long maxMemory) { |
| 68 |
this(maxMemory, 16, 8); |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Create a new cache with the given memory size. |
| 73 |
* |
| 74 |
* @param maxMemory the maximum memory to use (1 or larger) |
| 75 |
* @param segmentCount the number of cache segments (must be a power of 2) |
| 76 |
* @param stackMoveDistance how many other item are to be moved to the top |
| 77 |
* of the stack before the current item is moved |
| 78 |
*/ |
| 79 |
@SuppressWarnings("unchecked") |
| 80 |
public CacheLIRS(long maxMemory, int segmentCount, |
| 81 |
int stackMoveDistance) { |
| 82 |
setMaxMemory(maxMemory); |
| 83 |
if (Integer.bitCount(segmentCount) != 1) { |
| 84 |
throw new IllegalArgumentException( |
| 85 |
"The segment count must be a power of 2, is " |
| 86 |
+ segmentCount); |
| 87 |
} |
| 88 |
this.segmentCount = segmentCount; |
| 89 |
this.segmentMask = segmentCount - 1; |
| 90 |
this.stackMoveDistance = stackMoveDistance; |
| 91 |
segments = new Segment[segmentCount]; |
| 92 |
clear(); |
| 93 |
// use the high bits for the segment |
| 94 |
this.segmentShift = 32 - Integer.bitCount(segmentMask); |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* Remove all entries. |
| 99 |
*/ |
| 100 |
@Override |
| 101 |
public void clear() { |
| 102 |
long max = Math.max(1, maxMemory / segmentCount); |
| 103 |
for (int i = 0; i < segmentCount; i++) { |
| 104 |
segments[i] = new Segment<>( |
| 105 |
this, max, stackMoveDistance, 8); |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
private Entry<K, V> find(Object key) { |
| 110 |
int hash = getHash(key); |
| 111 |
return getSegment(hash).find(key, hash); |
| 112 |
} |
| 113 |
|
| 114 |
/** |
| 115 |
* Check whether there is a resident entry for the given key. This |
| 116 |
* method does not adjust the internal state of the cache. |
| 117 |
* |
| 118 |
* @param key the key (may not be null) |
| 119 |
* @return true if there is a resident entry |
| 120 |
*/ |
| 121 |
@Override |
| 122 |
public boolean containsKey(Object key) { |
| 123 |
int hash = getHash(key); |
| 124 |
return getSegment(hash).containsKey(key, hash); |
| 125 |
} |
| 126 |
|
| 127 |
/** |
| 128 |
* Get the value for the given key if the entry is cached. This method does |
| 129 |
* not modify the internal state. |
| 130 |
* |
| 131 |
* @param key the key (may not be null) |
| 132 |
* @return the value, or null if there is no resident entry |
| 133 |
*/ |
| 134 |
public V peek(K key) { |
| 135 |
Entry<K, V> e = find(key); |
| 136 |
return e == null ? null : e.value; |
| 137 |
} |
| 138 |
|
| 139 |
/** |
| 140 |
* Add an entry to the cache. The entry may or may not exist in the |
| 141 |
* cache yet. This method will usually mark unknown entries as cold and |
| 142 |
* known entries as hot. |
| 143 |
* |
| 144 |
* @param key the key (may not be null) |
| 145 |
* @param value the value (may not be null) |
| 146 |
* @param memory the memory used for the given entry |
| 147 |
* @return the old value, or null if there was no resident entry |
| 148 |
*/ |
| 149 |
public V put(K key, V value, int memory) { |
| 150 |
int hash = getHash(key); |
| 151 |
int segmentIndex = getSegmentIndex(hash); |
| 152 |
Segment<K, V> s = segments[segmentIndex]; |
| 153 |
// check whether resize is required: synchronize on s, to avoid |
| 154 |
// concurrent resizes (concurrent reads read |
| 155 |
// from the old segment) |
| 156 |
synchronized (s) { |
| 157 |
s = resizeIfNeeded(s, segmentIndex); |
| 158 |
return s.put(key, hash, value, memory); |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
private Segment<K, V> resizeIfNeeded(Segment<K, V> s, int segmentIndex) { |
| 163 |
int newLen = s.getNewMapLen(); |
| 164 |
if (newLen == 0) { |
| 165 |
return s; |
| 166 |
} |
| 167 |
// another thread might have resized |
| 168 |
// (as we retrieved the segment before synchronizing on it) |
| 169 |
Segment<K, V> s2 = segments[segmentIndex]; |
| 170 |
if (s == s2) { |
| 171 |
// no other thread resized, so we do |
| 172 |
s = new Segment<>(s, newLen); |
| 173 |
segments[segmentIndex] = s; |
| 174 |
} |
| 175 |
return s; |
| 176 |
} |
| 177 |
|
| 178 |
/** |
| 179 |
* Add an entry to the cache using a memory size of 1. |
| 180 |
* |
| 181 |
* @param key the key (may not be null) |
| 182 |
* @param value the value (may not be null) |
| 183 |
* @return the old value, or null if there was no resident entry |
| 184 |
*/ |
| 185 |
@Override |
| 186 |
public V put(K key, V value) { |
| 187 |
return put(key, value, sizeOf(key, value)); |
| 188 |
} |
| 189 |
|
| 190 |
/** |
| 191 |
* Get the size of the given value. The default implementation returns 1. |
| 192 |
* |
| 193 |
* @param key the key |
| 194 |
* @param value the value |
| 195 |
* @return the size |
| 196 |
*/ |
| 197 |
@SuppressWarnings("unused") |
| 198 |
protected int sizeOf(K key, V value) { |
| 199 |
return 1; |
| 200 |
} |
| 201 |
|
| 202 |
/** |
| 203 |
* This method is called after the value for the given key was removed. |
| 204 |
* It is not called on clear or put when replacing a value. |
| 205 |
* |
| 206 |
* @param key the key |
| 207 |
*/ |
| 208 |
protected void onRemove(@SuppressWarnings("unused") K key) { |
| 209 |
// do nothing |
| 210 |
} |
| 211 |
|
| 212 |
/** |
| 213 |
* Remove an entry. Both resident and non-resident entries can be |
| 214 |
* removed. |
| 215 |
* |
| 216 |
* @param key the key (may not be null) |
| 217 |
* @return the old value, or null if there was no resident entry |
| 218 |
*/ |
| 219 |
@Override |
| 220 |
public V remove(Object key) { |
| 221 |
int hash = getHash(key); |
| 222 |
int segmentIndex = getSegmentIndex(hash); |
| 223 |
Segment<K, V> s = segments[segmentIndex]; |
| 224 |
// check whether resize is required: synchronize on s, to avoid |
| 225 |
// concurrent resizes (concurrent reads read |
| 226 |
// from the old segment) |
| 227 |
synchronized (s) { |
| 228 |
s = resizeIfNeeded(s, segmentIndex); |
| 229 |
return s.remove(key, hash); |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
/** |
| 234 |
* Get the memory used for the given key. |
| 235 |
* |
| 236 |
* @param key the key (may not be null) |
| 237 |
* @return the memory, or 0 if there is no resident entry |
| 238 |
*/ |
| 239 |
public int getMemory(K key) { |
| 240 |
int hash = getHash(key); |
| 241 |
return getSegment(hash).getMemory(key, hash); |
| 242 |
} |
| 243 |
|
| 244 |
/** |
| 245 |
* Get the value for the given key if the entry is cached. This method |
| 246 |
* adjusts the internal state of the cache sometimes, to ensure commonly |
| 247 |
* used entries stay in the cache. |
| 248 |
* |
| 249 |
* @param key the key (may not be null) |
| 250 |
* @return the value, or null if there is no resident entry |
| 251 |
*/ |
| 252 |
@Override |
| 253 |
public V get(Object key) { |
| 254 |
int hash = getHash(key); |
| 255 |
return getSegment(hash).get(key, hash); |
| 256 |
} |
| 257 |
|
| 258 |
private Segment<K, V> getSegment(int hash) { |
| 259 |
return segments[getSegmentIndex(hash)]; |
| 260 |
} |
| 261 |
|
| 262 |
private int getSegmentIndex(int hash) { |
| 263 |
return (hash >>> segmentShift) & segmentMask; |
| 264 |
} |
| 265 |
|
| 266 |
/** |
| 267 |
* Get the hash code for the given key. The hash code is |
| 268 |
* further enhanced to spread the values more evenly. |
| 269 |
* |
| 270 |
* @param key the key |
| 271 |
* @return the hash code |
| 272 |
*/ |
| 273 |
static int getHash(Object key) { |
| 274 |
int hash = key.hashCode(); |
| 275 |
// a supplemental secondary hash function |
| 276 |
// to protect against hash codes that don't differ much |
| 277 |
hash = ((hash >>> 16) ^ hash) * 0x45d9f3b; |
| 278 |
hash = ((hash >>> 16) ^ hash) * 0x45d9f3b; |
| 279 |
hash = (hash >>> 16) ^ hash; |
| 280 |
return hash; |
| 281 |
} |
| 282 |
|
| 283 |
/** |
| 284 |
* Get the currently used memory. |
| 285 |
* |
| 286 |
* @return the used memory |
| 287 |
*/ |
| 288 |
public long getUsedMemory() { |
| 289 |
long x = 0; |
| 290 |
for (Segment<K, V> s : segments) { |
| 291 |
x += s.usedMemory; |
| 292 |
} |
| 293 |
return x; |
| 294 |
} |
| 295 |
|
| 296 |
/** |
| 297 |
* Set the maximum memory this cache should use. This will not |
| 298 |
* immediately cause entries to get removed however; it will only change |
| 299 |
* the limit. To resize the internal array, call the clear method. |
| 300 |
* |
| 301 |
* @param maxMemory the maximum size (1 or larger) |
| 302 |
*/ |
| 303 |
public void setMaxMemory(long maxMemory) { |
| 304 |
if (maxMemory <= 0) { |
| 305 |
throw new IllegalArgumentException("Max memory must be larger than 0"); |
| 306 |
} |
| 307 |
this.maxMemory = maxMemory; |
| 308 |
if (segments != null) { |
| 309 |
long max = 1 + maxMemory / segments.length; |
| 310 |
for (Segment<K, V> s : segments) { |
| 311 |
s.setMaxMemory(max); |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
/** |
| 317 |
* Get the maximum memory to use. |
| 318 |
* |
| 319 |
* @return the maximum memory |
| 320 |
*/ |
| 321 |
public long getMaxMemory() { |
| 322 |
return maxMemory; |
| 323 |
} |
| 324 |
|
| 325 |
/** |
| 326 |
* Get the entry set for all resident entries. |
| 327 |
* |
| 328 |
* @return the entry set |
| 329 |
*/ |
| 330 |
@Override |
| 331 |
public Set<Map.Entry<K, V>> entrySet() { |
| 332 |
HashMap<K, V> map = new HashMap<>(); |
| 333 |
for (K k : keySet()) { |
| 334 |
map.put(k, find(k).value); |
| 335 |
} |
| 336 |
return map.entrySet(); |
| 337 |
} |
| 338 |
|
| 339 |
/** |
| 340 |
* Get the set of keys for resident entries. |
| 341 |
* |
| 342 |
* @return the set of keys |
| 343 |
*/ |
| 344 |
@Override |
| 345 |
public Set<K> keySet() { |
| 346 |
HashSet<K> set = new HashSet<>(); |
| 347 |
for (Segment<K, V> s : segments) { |
| 348 |
set.addAll(s.keySet()); |
| 349 |
} |
| 350 |
return set; |
| 351 |
} |
| 352 |
|
| 353 |
/** |
| 354 |
* Get the number of non-resident entries in the cache. |
| 355 |
* |
| 356 |
* @return the number of non-resident entries |
| 357 |
*/ |
| 358 |
public int sizeNonResident() { |
| 359 |
int x = 0; |
| 360 |
for (Segment<K, V> s : segments) { |
| 361 |
x += s.queue2Size; |
| 362 |
} |
| 363 |
return x; |
| 364 |
} |
| 365 |
|
| 366 |
/** |
| 367 |
* Get the length of the internal map array. |
| 368 |
* |
| 369 |
* @return the size of the array |
| 370 |
*/ |
| 371 |
public int sizeMapArray() { |
| 372 |
int x = 0; |
| 373 |
for (Segment<K, V> s : segments) { |
| 374 |
x += s.entries.length; |
| 375 |
} |
| 376 |
return x; |
| 377 |
} |
| 378 |
|
| 379 |
/** |
| 380 |
* Get the number of hot entries in the cache. |
| 381 |
* |
| 382 |
* @return the number of hot entries |
| 383 |
*/ |
| 384 |
public int sizeHot() { |
| 385 |
int x = 0; |
| 386 |
for (Segment<K, V> s : segments) { |
| 387 |
x += s.mapSize - s.queueSize - s.queue2Size; |
| 388 |
} |
| 389 |
return x; |
| 390 |
} |
| 391 |
|
| 392 |
/** |
| 393 |
* Get the number of resident entries. |
| 394 |
* |
| 395 |
* @return the number of entries |
| 396 |
*/ |
| 397 |
@Override |
| 398 |
public int size() { |
| 399 |
int x = 0; |
| 400 |
for (Segment<K, V> s : segments) { |
| 401 |
x += s.mapSize - s.queue2Size; |
| 402 |
} |
| 403 |
return x; |
| 404 |
} |
| 405 |
|
| 406 |
/** |
| 407 |
* Get the list of keys. This method allows to read the internal state of |
| 408 |
* the cache. |
| 409 |
* |
| 410 |
* @param cold if true, only keys for the cold entries are returned |
| 411 |
* @param nonResident true for non-resident entries |
| 412 |
* @return the key list |
| 413 |
*/ |
| 414 |
public List<K> keys(boolean cold, boolean nonResident) { |
| 415 |
ArrayList<K> keys = new ArrayList<>(); |
| 416 |
for (Segment<K, V> s : segments) { |
| 417 |
keys.addAll(s.keys(cold, nonResident)); |
| 418 |
} |
| 419 |
return keys; |
| 420 |
} |
| 421 |
|
| 422 |
/** |
| 423 |
* A cache segment |
| 424 |
* |
| 425 |
* @param <K> the key type |
| 426 |
* @param <V> the value type |
| 427 |
*/ |
| 428 |
private static class Segment<K, V> { |
| 429 |
|
| 430 |
/** |
| 431 |
* The number of (hot, cold, and non-resident) entries in the map. |
| 432 |
*/ |
| 433 |
int mapSize; |
| 434 |
|
| 435 |
/** |
| 436 |
* The size of the LIRS queue for resident cold entries. |
| 437 |
*/ |
| 438 |
int queueSize; |
| 439 |
|
| 440 |
/** |
| 441 |
* The size of the LIRS queue for non-resident cold entries. |
| 442 |
*/ |
| 443 |
int queue2Size; |
| 444 |
|
| 445 |
/** |
| 446 |
* The map array. The size is always a power of 2. |
| 447 |
*/ |
| 448 |
final Entry<K, V>[] entries; |
| 449 |
|
| 450 |
/** |
| 451 |
* The currently used memory. |
| 452 |
*/ |
| 453 |
long usedMemory; |
| 454 |
|
| 455 |
private final CacheLIRS<K, V> cache; |
| 456 |
|
| 457 |
/** |
| 458 |
* How many other item are to be moved to the top of the stack before |
| 459 |
* the current item is moved. |
| 460 |
*/ |
| 461 |
private final int stackMoveDistance; |
| 462 |
|
| 463 |
/** |
| 464 |
* The maximum memory this cache should use. |
| 465 |
*/ |
| 466 |
private long maxMemory; |
| 467 |
|
| 468 |
/** |
| 469 |
* The bit mask that is applied to the key hash code to get the index in |
| 470 |
* the map array. The mask is the length of the array minus one. |
| 471 |
*/ |
| 472 |
private final int mask; |
| 473 |
|
| 474 |
/** |
| 475 |
* The stack of recently referenced elements. This includes all hot |
| 476 |
* entries, and the recently referenced cold entries. Resident cold |
| 477 |
* entries that were not recently referenced, as well as non-resident |
| 478 |
* cold entries, are not in the stack. |
| 479 |
* <p> |
| 480 |
* There is always at least one entry: the head entry. |
| 481 |
*/ |
| 482 |
private final Entry<K, V> stack; |
| 483 |
|
| 484 |
/** |
| 485 |
* The number of entries in the stack. |
| 486 |
*/ |
| 487 |
private int stackSize; |
| 488 |
|
| 489 |
/** |
| 490 |
* The queue of resident cold entries. |
| 491 |
* <p> |
| 492 |
* There is always at least one entry: the head entry. |
| 493 |
*/ |
| 494 |
private final Entry<K, V> queue; |
| 495 |
|
| 496 |
/** |
| 497 |
* The queue of non-resident cold entries. |
| 498 |
* <p> |
| 499 |
* There is always at least one entry: the head entry. |
| 500 |
*/ |
| 501 |
private final Entry<K, V> queue2; |
| 502 |
|
| 503 |
/** |
| 504 |
* The number of times any item was moved to the top of the stack. |
| 505 |
*/ |
| 506 |
private int stackMoveCounter; |
| 507 |
|
| 508 |
/** |
| 509 |
* Create a new cache segment. |
| 510 |
* |
| 511 |
* @param cache the cache |
| 512 |
* @param maxMemory the maximum memory to use |
| 513 |
* @param stackMoveDistance the number of other entries to be moved to |
| 514 |
* the top of the stack before moving an entry to the top |
| 515 |
* @param len the number of hash table buckets (must be a power of 2) |
| 516 |
*/ |
| 517 |
Segment(CacheLIRS<K, V> cache, long maxMemory, |
| 518 |
int stackMoveDistance, int len) { |
| 519 |
this.cache = cache; |
| 520 |
setMaxMemory(maxMemory); |
| 521 |
this.stackMoveDistance = stackMoveDistance; |
| 522 |
|
| 523 |
// the bit mask has all bits set |
| 524 |
mask = len - 1; |
| 525 |
|
| 526 |
// initialize the stack and queue heads |
| 527 |
stack = new Entry<>(); |
| 528 |
stack.stackPrev = stack.stackNext = stack; |
| 529 |
queue = new Entry<>(); |
| 530 |
queue.queuePrev = queue.queueNext = queue; |
| 531 |
queue2 = new Entry<>(); |
| 532 |
queue2.queuePrev = queue2.queueNext = queue2; |
| 533 |
|
| 534 |
@SuppressWarnings("unchecked") |
| 535 |
Entry<K, V>[] e = new Entry[len]; |
| 536 |
entries = e; |
| 537 |
} |
| 538 |
|
| 539 |
/** |
| 540 |
* Create a new cache segment from an existing one. |
| 541 |
* The caller must synchronize on the old segment, to avoid |
| 542 |
* concurrent modifications. |
| 543 |
* |
| 544 |
* @param old the old segment |
| 545 |
* @param len the number of hash table buckets (must be a power of 2) |
| 546 |
*/ |
| 547 |
Segment(Segment<K, V> old, int len) { |
| 548 |
this(old.cache, old.maxMemory, old.stackMoveDistance, len); |
| 549 |
Entry<K, V> s = old.stack.stackPrev; |
| 550 |
while (s != old.stack) { |
| 551 |
Entry<K, V> e = copy(s); |
| 552 |
addToMap(e); |
| 553 |
addToStack(e); |
| 554 |
s = s.stackPrev; |
| 555 |
} |
| 556 |
s = old.queue.queuePrev; |
| 557 |
while (s != old.queue) { |
| 558 |
Entry<K, V> e = find(s.key, getHash(s.key)); |
| 559 |
if (e == null) { |
| 560 |
e = copy(s); |
| 561 |
addToMap(e); |
| 562 |
} |
| 563 |
addToQueue(queue, e); |
| 564 |
s = s.queuePrev; |
| 565 |
} |
| 566 |
s = old.queue2.queuePrev; |
| 567 |
while (s != old.queue2) { |
| 568 |
Entry<K, V> e = find(s.key, getHash(s.key)); |
| 569 |
if (e == null) { |
| 570 |
e = copy(s); |
| 571 |
addToMap(e); |
| 572 |
} |
| 573 |
addToQueue(queue2, e); |
| 574 |
s = s.queuePrev; |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
/** |
| 579 |
* Calculate the new number of hash table buckets if the internal map |
| 580 |
* should be re-sized. |
| 581 |
* |
| 582 |
* @return 0 if no resizing is needed, or the new length |
| 583 |
*/ |
| 584 |
int getNewMapLen() { |
| 585 |
int len = mask + 1; |
| 586 |
if (len * 3 < mapSize * 4 && len < (1 << 28)) { |
| 587 |
// more than 75% usage |
| 588 |
return len * 2; |
| 589 |
} else if (len > 32 && len / 8 > mapSize) { |
| 590 |
// less than 12% usage |
| 591 |
return len / 2; |
| 592 |
} |
| 593 |
return 0; |
| 594 |
} |
| 595 |
|
| 596 |
private void addToMap(Entry<K, V> e) { |
| 597 |
int index = getHash(e.key) & mask; |
| 598 |
e.mapNext = entries[index]; |
| 599 |
entries[index] = e; |
| 600 |
usedMemory += e.memory; |
| 601 |
mapSize++; |
| 602 |
} |
| 603 |
|
| 604 |
private static <K, V> Entry<K, V> copy(Entry<K, V> old) { |
| 605 |
Entry<K, V> e = new Entry<>(); |
| 606 |
e.key = old.key; |
| 607 |
e.value = old.value; |
| 608 |
e.memory = old.memory; |
| 609 |
e.topMove = old.topMove; |
| 610 |
return e; |
| 611 |
} |
| 612 |
|
| 613 |
/** |
| 614 |
* Get the memory used for the given key. |
| 615 |
* |
| 616 |
* @param key the key (may not be null) |
| 617 |
* @param hash the hash |
| 618 |
* @return the memory, or 0 if there is no resident entry |
| 619 |
*/ |
| 620 |
int getMemory(K key, int hash) { |
| 621 |
Entry<K, V> e = find(key, hash); |
| 622 |
return e == null ? 0 : e.memory; |
| 623 |
} |
| 624 |
|
| 625 |
/** |
| 626 |
* Get the value for the given key if the entry is cached. This method |
| 627 |
* adjusts the internal state of the cache sometimes, to ensure commonly |
| 628 |
* used entries stay in the cache. |
| 629 |
* |
| 630 |
* @param key the key (may not be null) |
| 631 |
* @param hash the hash |
| 632 |
* @return the value, or null if there is no resident entry |
| 633 |
*/ |
| 634 |
V get(Object key, int hash) { |
| 635 |
Entry<K, V> e = find(key, hash); |
| 636 |
if (e == null) { |
| 637 |
// the entry was not found |
| 638 |
return null; |
| 639 |
} |
| 640 |
V value = e.value; |
| 641 |
if (value == null) { |
| 642 |
// it was a non-resident entry |
| 643 |
return null; |
| 644 |
} |
| 645 |
if (e.isHot()) { |
| 646 |
if (e != stack.stackNext) { |
| 647 |
if (stackMoveDistance == 0 || |
| 648 |
stackMoveCounter - e.topMove > stackMoveDistance) { |
| 649 |
access(key, hash); |
| 650 |
} |
| 651 |
} |
| 652 |
} else { |
| 653 |
access(key, hash); |
| 654 |
} |
| 655 |
return value; |
| 656 |
} |
| 657 |
|
| 658 |
/** |
| 659 |
* Access an item, moving the entry to the top of the stack or front of |
| 660 |
* the queue if found. |
| 661 |
* |
| 662 |
* @param key the key |
| 663 |
*/ |
| 664 |
private synchronized void access(Object key, int hash) { |
| 665 |
Entry<K, V> e = find(key, hash); |
| 666 |
if (e == null || e.value == null) { |
| 667 |
return; |
| 668 |
} |
| 669 |
if (e.isHot()) { |
| 670 |
if (e != stack.stackNext) { |
| 671 |
if (stackMoveDistance == 0 || |
| 672 |
stackMoveCounter - e.topMove > stackMoveDistance) { |
| 673 |
// move a hot entry to the top of the stack |
| 674 |
// unless it is already there |
| 675 |
boolean wasEnd = e == stack.stackPrev; |
| 676 |
removeFromStack(e); |
| 677 |
if (wasEnd) { |
| 678 |
// if moving the last entry, the last entry |
| 679 |
// could now be cold, which is not allowed |
| 680 |
pruneStack(); |
| 681 |
} |
| 682 |
addToStack(e); |
| 683 |
} |
| 684 |
} |
| 685 |
} else { |
| 686 |
removeFromQueue(e); |
| 687 |
if (e.stackNext != null) { |
| 688 |
// resident cold entries become hot |
| 689 |
// if they are on the stack |
| 690 |
removeFromStack(e); |
| 691 |
// which means a hot entry needs to become cold |
| 692 |
// (this entry is cold, that means there is at least one |
| 693 |
// more entry in the stack, which must be hot) |
| 694 |
convertOldestHotToCold(); |
| 695 |
} else { |
| 696 |
// cold entries that are not on the stack |
| 697 |
// move to the front of the queue |
| 698 |
addToQueue(queue, e); |
| 699 |
} |
| 700 |
// in any case, the cold entry is moved to the top of the stack |
| 701 |
addToStack(e); |
| 702 |
} |
| 703 |
} |
| 704 |
|
| 705 |
/** |
| 706 |
* Add an entry to the cache. The entry may or may not exist in the |
| 707 |
* cache yet. This method will usually mark unknown entries as cold and |
| 708 |
* known entries as hot. |
| 709 |
* |
| 710 |
* @param key the key (may not be null) |
| 711 |
* @param hash the hash |
| 712 |
* @param value the value (may not be null) |
| 713 |
* @param memory the memory used for the given entry |
| 714 |
* @return the old value, or null if there was no resident entry |
| 715 |
*/ |
| 716 |
synchronized V put(K key, int hash, V value, int memory) { |
| 717 |
if (value == null) { |
| 718 |
throw new NullPointerException("The value may not be null"); |
| 719 |
} |
| 720 |
V old; |
| 721 |
Entry<K, V> e = find(key, hash); |
| 722 |
if (e == null) { |
| 723 |
old = null; |
| 724 |
} else { |
| 725 |
old = e.value; |
| 726 |
remove(key, hash); |
| 727 |
} |
| 728 |
if (memory > maxMemory) { |
| 729 |
// the new entry is too big to fit |
| 730 |
return old; |
| 731 |
} |
| 732 |
e = new Entry<>(); |
| 733 |
e.key = key; |
| 734 |
e.value = value; |
| 735 |
e.memory = memory; |
| 736 |
int index = hash & mask; |
| 737 |
e.mapNext = entries[index]; |
| 738 |
entries[index] = e; |
| 739 |
usedMemory += memory; |
| 740 |
if (usedMemory > maxMemory) { |
| 741 |
// old entries needs to be removed |
| 742 |
evict(); |
| 743 |
// if the cache is full, the new entry is |
| 744 |
// cold if possible |
| 745 |
if (stackSize > 0) { |
| 746 |
// the new cold entry is at the top of the queue |
| 747 |
addToQueue(queue, e); |
| 748 |
} |
| 749 |
} |
| 750 |
mapSize++; |
| 751 |
// added entries are always added to the stack |
| 752 |
addToStack(e); |
| 753 |
return old; |
| 754 |
} |
| 755 |
|
| 756 |
/** |
| 757 |
* Remove an entry. Both resident and non-resident entries can be |
| 758 |
* removed. |
| 759 |
* |
| 760 |
* @param key the key (may not be null) |
| 761 |
* @param hash the hash |
| 762 |
* @return the old value, or null if there was no resident entry |
| 763 |
*/ |
| 764 |
synchronized V remove(Object key, int hash) { |
| 765 |
int index = hash & mask; |
| 766 |
Entry<K, V> e = entries[index]; |
| 767 |
if (e == null) { |
| 768 |
return null; |
| 769 |
} |
| 770 |
V old; |
| 771 |
if (e.key.equals(key)) { |
| 772 |
old = e.value; |
| 773 |
entries[index] = e.mapNext; |
| 774 |
} else { |
| 775 |
Entry<K, V> last; |
| 776 |
do { |
| 777 |
last = e; |
| 778 |
e = e.mapNext; |
| 779 |
if (e == null) { |
| 780 |
return null; |
| 781 |
} |
| 782 |
} while (!e.key.equals(key)); |
| 783 |
old = e.value; |
| 784 |
last.mapNext = e.mapNext; |
| 785 |
} |
| 786 |
mapSize--; |
| 787 |
usedMemory -= e.memory; |
| 788 |
if (e.stackNext != null) { |
| 789 |
removeFromStack(e); |
| 790 |
} |
| 791 |
if (e.isHot()) { |
| 792 |
// when removing a hot entry, the newest cold entry gets hot, |
| 793 |
// so the number of hot entries does not change |
| 794 |
e = queue.queueNext; |
| 795 |
if (e != queue) { |
| 796 |
removeFromQueue(e); |
| 797 |
if (e.stackNext == null) { |
| 798 |
addToStackBottom(e); |
| 799 |
} |
| 800 |
} |
| 801 |
} else { |
| 802 |
removeFromQueue(e); |
| 803 |
} |
| 804 |
pruneStack(); |
| 805 |
return old; |
| 806 |
} |
| 807 |
|
| 808 |
/** |
| 809 |
* Evict cold entries (resident and non-resident) until the memory limit |
| 810 |
* is reached. The new entry is added as a cold entry, except if it is |
| 811 |
* the only entry. |
| 812 |
*/ |
| 813 |
private void evict() { |
| 814 |
do { |
| 815 |
evictBlock(); |
| 816 |
} while (usedMemory > maxMemory); |
| 817 |
} |
| 818 |
|
| 819 |
private void evictBlock() { |
| 820 |
// ensure there are not too many hot entries: right shift of 5 is |
| 821 |
// division by 32, that means if there are only 1/32 (3.125%) or |
| 822 |
// less cold entries, a hot entry needs to become cold |
| 823 |
while (queueSize <= (mapSize >>> 5) && stackSize > 0) { |
| 824 |
convertOldestHotToCold(); |
| 825 |
} |
| 826 |
// the oldest resident cold entries become non-resident |
| 827 |
while (usedMemory > maxMemory && queueSize > 0) { |
| 828 |
Entry<K, V> e = queue.queuePrev; |
| 829 |
usedMemory -= e.memory; |
| 830 |
removeFromQueue(e); |
| 831 |
cache.onRemove(e.key); |
| 832 |
e.value = null; |
| 833 |
e.memory = 0; |
| 834 |
addToQueue(queue2, e); |
| 835 |
// the size of the non-resident-cold entries needs to be limited |
| 836 |
while (queue2Size + queue2Size > stackSize) { |
| 837 |
e = queue2.queuePrev; |
| 838 |
int hash = getHash(e.key); |
| 839 |
remove(e.key, hash); |
| 840 |
} |
| 841 |
} |
| 842 |
} |
| 843 |
|
| 844 |
private void convertOldestHotToCold() { |
| 845 |
// the last entry of the stack is known to be hot |
| 846 |
Entry<K, V> last = stack.stackPrev; |
| 847 |
if (last == stack) { |
| 848 |
// never remove the stack head itself (this would mean the |
| 849 |
// internal structure of the cache is corrupt) |
| 850 |
throw new IllegalStateException(); |
| 851 |
} |
| 852 |
// remove from stack - which is done anyway in the stack pruning, |
| 853 |
// but we can do it here as well |
| 854 |
removeFromStack(last); |
| 855 |
// adding an entry to the queue will make it cold |
| 856 |
addToQueue(queue, last); |
| 857 |
pruneStack(); |
| 858 |
} |
| 859 |
|
| 860 |
/** |
| 861 |
* Ensure the last entry of the stack is cold. |
| 862 |
*/ |
| 863 |
private void pruneStack() { |
| 864 |
while (true) { |
| 865 |
Entry<K, V> last = stack.stackPrev; |
| 866 |
// must stop at a hot entry or the stack head, |
| 867 |
// but the stack head itself is also hot, so we |
| 868 |
// don't have to test it |
| 869 |
if (last.isHot()) { |
| 870 |
break; |
| 871 |
} |
| 872 |
// the cold entry is still in the queue |
| 873 |
removeFromStack(last); |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
/** |
| 878 |
* Try to find an entry in the map. |
| 879 |
* |
| 880 |
* @param key the key |
| 881 |
* @param hash the hash |
| 882 |
* @return the entry (might be a non-resident) |
| 883 |
*/ |
| 884 |
Entry<K, V> find(Object key, int hash) { |
| 885 |
int index = hash & mask; |
| 886 |
Entry<K, V> e = entries[index]; |
| 887 |
while (e != null && !e.key.equals(key)) { |
| 888 |
e = e.mapNext; |
| 889 |
} |
| 890 |
return e; |
| 891 |
} |
| 892 |
|
| 893 |
private void addToStack(Entry<K, V> e) { |
| 894 |
e.stackPrev = stack; |
| 895 |
e.stackNext = stack.stackNext; |
| 896 |
e.stackNext.stackPrev = e; |
| 897 |
stack.stackNext = e; |
| 898 |
stackSize++; |
| 899 |
e.topMove = stackMoveCounter++; |
| 900 |
} |
| 901 |
|
| 902 |
private void addToStackBottom(Entry<K, V> e) { |
| 903 |
e.stackNext = stack; |
| 904 |
e.stackPrev = stack.stackPrev; |
| 905 |
e.stackPrev.stackNext = e; |
| 906 |
stack.stackPrev = e; |
| 907 |
stackSize++; |
| 908 |
} |
| 909 |
|
| 910 |
/** |
| 911 |
* Remove the entry from the stack. The head itself must not be removed. |
| 912 |
* |
| 913 |
* @param e the entry |
| 914 |
*/ |
| 915 |
private void removeFromStack(Entry<K, V> e) { |
| 916 |
e.stackPrev.stackNext = e.stackNext; |
| 917 |
e.stackNext.stackPrev = e.stackPrev; |
| 918 |
e.stackPrev = e.stackNext = null; |
| 919 |
stackSize--; |
| 920 |
} |
| 921 |
|
| 922 |
private void addToQueue(Entry<K, V> q, Entry<K, V> e) { |
| 923 |
e.queuePrev = q; |
| 924 |
e.queueNext = q.queueNext; |
| 925 |
e.queueNext.queuePrev = e; |
| 926 |
q.queueNext = e; |
| 927 |
if (e.value != null) { |
| 928 |
queueSize++; |
| 929 |
} else { |
| 930 |
queue2Size++; |
| 931 |
} |
| 932 |
} |
| 933 |
|
| 934 |
private void removeFromQueue(Entry<K, V> e) { |
| 935 |
e.queuePrev.queueNext = e.queueNext; |
| 936 |
e.queueNext.queuePrev = e.queuePrev; |
| 937 |
e.queuePrev = e.queueNext = null; |
| 938 |
if (e.value != null) { |
| 939 |
queueSize--; |
| 940 |
} else { |
| 941 |
queue2Size--; |
| 942 |
} |
| 943 |
} |
| 944 |
|
| 945 |
/** |
| 946 |
* Get the list of keys. This method allows to read the internal state |
| 947 |
* of the cache. |
| 948 |
* |
| 949 |
* @param cold if true, only keys for the cold entries are returned |
| 950 |
* @param nonResident true for non-resident entries |
| 951 |
* @return the key list |
| 952 |
*/ |
| 953 |
synchronized List<K> keys(boolean cold, boolean nonResident) { |
| 954 |
ArrayList<K> keys = new ArrayList<>(); |
| 955 |
if (cold) { |
| 956 |
Entry<K, V> start = nonResident ? queue2 : queue; |
| 957 |
for (Entry<K, V> e = start.queueNext; e != start; |
| 958 |
e = e.queueNext) { |
| 959 |
keys.add(e.key); |
| 960 |
} |
| 961 |
} else { |
| 962 |
for (Entry<K, V> e = stack.stackNext; e != stack; |
| 963 |
e = e.stackNext) { |
| 964 |
keys.add(e.key); |
| 965 |
} |
| 966 |
} |
| 967 |
return keys; |
| 968 |
} |
| 969 |
|
| 970 |
/** |
| 971 |
* Check whether there is a resident entry for the given key. This |
| 972 |
* method does not adjust the internal state of the cache. |
| 973 |
* |
| 974 |
* @param key the key (may not be null) |
| 975 |
* @param hash the hash |
| 976 |
* @return true if there is a resident entry |
| 977 |
*/ |
| 978 |
boolean containsKey(Object key, int hash) { |
| 979 |
Entry<K, V> e = find(key, hash); |
| 980 |
return e != null && e.value != null; |
| 981 |
} |
| 982 |
|
| 983 |
/** |
| 984 |
* Get the set of keys for resident entries. |
| 985 |
* |
| 986 |
* @return the set of keys |
| 987 |
*/ |
| 988 |
synchronized Set<K> keySet() { |
| 989 |
HashSet<K> set = new HashSet<>(); |
| 990 |
for (Entry<K, V> e = stack.stackNext; e != stack; e = e.stackNext) { |
| 991 |
set.add(e.key); |
| 992 |
} |
| 993 |
for (Entry<K, V> e = queue.queueNext; e != queue; e = e.queueNext) { |
| 994 |
set.add(e.key); |
| 995 |
} |
| 996 |
return set; |
| 997 |
} |
| 998 |
|
| 999 |
/** |
| 1000 |
* Set the maximum memory this cache should use. This will not |
| 1001 |
* immediately cause entries to get removed however; it will only change |
| 1002 |
* the limit. To resize the internal array, call the clear method. |
| 1003 |
* |
| 1004 |
* @param maxMemory the maximum size (1 or larger) |
| 1005 |
*/ |
| 1006 |
void setMaxMemory(long maxMemory) { |
| 1007 |
this.maxMemory = maxMemory; |
| 1008 |
} |
| 1009 |
|
| 1010 |
} |
| 1011 |
|
| 1012 |
/** |
| 1013 |
* A cache entry. Each entry is either hot (low inter-reference recency; |
| 1014 |
* LIR), cold (high inter-reference recency; HIR), or non-resident-cold. Hot |
| 1015 |
* entries are in the stack only. Cold entries are in the queue, and may be |
| 1016 |
* in the stack. Non-resident-cold entries have their value set to null and |
| 1017 |
* are in the stack and in the non-resident queue. |
| 1018 |
* |
| 1019 |
* @param <K> the key type |
| 1020 |
* @param <V> the value type |
| 1021 |
*/ |
| 1022 |
static class Entry<K, V> { |
| 1023 |
|
| 1024 |
/** |
| 1025 |
* The key. |
| 1026 |
*/ |
| 1027 |
K key; |
| 1028 |
|
| 1029 |
/** |
| 1030 |
* The value. Set to null for non-resident-cold entries. |
| 1031 |
*/ |
| 1032 |
V value; |
| 1033 |
|
| 1034 |
/** |
| 1035 |
* The estimated memory used. |
| 1036 |
*/ |
| 1037 |
int memory; |
| 1038 |
|
| 1039 |
/** |
| 1040 |
* When the item was last moved to the top of the stack. |
| 1041 |
*/ |
| 1042 |
int topMove; |
| 1043 |
|
| 1044 |
/** |
| 1045 |
* The next entry in the stack. |
| 1046 |
*/ |
| 1047 |
Entry<K, V> stackNext; |
| 1048 |
|
| 1049 |
/** |
| 1050 |
* The previous entry in the stack. |
| 1051 |
*/ |
| 1052 |
Entry<K, V> stackPrev; |
| 1053 |
|
| 1054 |
/** |
| 1055 |
* The next entry in the queue (either the resident queue or the |
| 1056 |
* non-resident queue). |
| 1057 |
*/ |
| 1058 |
Entry<K, V> queueNext; |
| 1059 |
|
| 1060 |
/** |
| 1061 |
* The previous entry in the queue. |
| 1062 |
*/ |
| 1063 |
Entry<K, V> queuePrev; |
| 1064 |
|
| 1065 |
/** |
| 1066 |
* The next entry in the map (the chained entry). |
| 1067 |
*/ |
| 1068 |
Entry<K, V> mapNext; |
| 1069 |
|
| 1070 |
/** |
| 1071 |
* Whether this entry is hot. Cold entries are in one of the two queues. |
| 1072 |
* |
| 1073 |
* @return whether the entry is hot |
| 1074 |
*/ |
| 1075 |
boolean isHot() { |
| 1076 |
return queueNext == null; |
| 1077 |
} |
| 1078 |
|
| 1079 |
} |
| 1080 |
|
| 1081 |
} |