Debian Codegraph @

src/main/org/h2/mvstore/cache/CacheLongKeyLIRS.java

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