-
Notifications
You must be signed in to change notification settings - Fork 391
/
Int2ObjectCache.java
887 lines (770 loc) · 21.2 KB
/
Int2ObjectCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
* Copyright 2014-2021 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.agrona.collections;
import org.agrona.generation.DoNotSub;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import static java.util.Objects.requireNonNull;
import static org.agrona.collections.CollectionUtil.validatePositivePowerOfTwo;
/**
* A cache implementation specialised for int keys using open addressing to probe a set of fixed size.
* <p>
* The eviction strategy is to remove the oldest in a set if the key is not found, or if found then that item.
* The newly inserted item becomes the youngest in the set. Sets are evicted on a first in, first out, manner unless
* replacing a matching key.
* <p>
* A good set size would be in the range of 2 to 16 so that the references/keys can fit in a cache-line (assuming
* references are 32-bit references and 64-byte cache lines, YMMV). A linear search within a cache line is much
* less costly than a cache-miss to another line.
* <p>
* Null values are not supported by this cache.
*
* @param <V> type of values stored in the {@link Map}
*/
public class Int2ObjectCache<V> implements Map<Integer, V>
{
private long cachePuts = 0;
private long cacheHits = 0;
private long cacheMisses = 0;
@DoNotSub private int size;
@DoNotSub private final int capacity;
@DoNotSub private final int setSize;
@DoNotSub private final int setSizeShift;
@DoNotSub private final int mask;
private final int[] keys;
private final Object[] values;
private final Consumer<V> evictionConsumer;
private ValueCollection valueCollection;
private KeySet keySet;
private EntrySet entrySet;
/**
* Constructs cache with provided configuration.
*
* @param numSets number of sets, must be power or two.
* @param setSize size of a single set, must be power or two.
* @param evictionConsumer consumer to be notified when entry is being evicted from the cache.
*/
public Int2ObjectCache(
@DoNotSub final int numSets,
@DoNotSub final int setSize,
final Consumer<V> evictionConsumer)
{
validatePositivePowerOfTwo(numSets);
validatePositivePowerOfTwo(setSize);
requireNonNull(evictionConsumer, "null values are not permitted");
if (((long)numSets) * setSize > (Integer.MAX_VALUE - 8))
{
throw new IllegalArgumentException(
"total capacity must be <= max array size: numSets=" + numSets + " setSize=" + setSize);
}
this.setSize = setSize;
this.setSizeShift = Integer.numberOfTrailingZeros(setSize);
capacity = numSets << setSizeShift;
mask = numSets - 1;
keys = new int[capacity];
values = new Object[capacity];
this.evictionConsumer = evictionConsumer;
}
/**
* The number of times a cache hit has occurred on the {@link #get(int)} method.
*
* @return the number of times a cache hit has occurred on the {@link #get(int)} method.
*/
public long cacheHits()
{
return cacheHits;
}
/**
* The number of times a cache miss has occurred on the {@link #get(int)} method.
*
* @return the number of times a cache miss has occurred on the {@link #get(int)} method.
*/
public long cacheMisses()
{
return cacheMisses;
}
/**
* The number of items that have been put in the cache.
*
* @return number of items that have been put in the cache.
*/
public long cachePuts()
{
return cachePuts;
}
/**
* Reset the cache statistics counters to zero.
*/
public void resetCounters()
{
cacheHits = 0;
cacheMisses = 0;
cachePuts = 0;
}
/**
* Get the total capacity for the map to which the load factor will be a fraction of.
*
* @return the total capacity for the map.
*/
@DoNotSub public int capacity()
{
return capacity;
}
/**
* {@inheritDoc}
*/
@DoNotSub public int size()
{
return size;
}
/**
* {@inheritDoc}
*/
public boolean isEmpty()
{
return 0 == size;
}
/**
* {@inheritDoc}
*/
public boolean containsKey(final Object key)
{
return containsKey(((Integer)key).intValue());
}
/**
* Overloaded version of {@link Map#containsKey(Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @return true if the key is found otherwise false.
*/
public boolean containsKey(final int key)
{
boolean found = false;
@DoNotSub final int setNumber = Hashing.hash(key, mask);
@DoNotSub final int setBeginIndex = setNumber << setSizeShift;
for (@DoNotSub int i = setBeginIndex, setEndIndex = setBeginIndex + setSize; i < setEndIndex; i++)
{
if (null == values[i])
{
break;
}
if (key == keys[i])
{
found = true;
break;
}
}
return found;
}
/**
* {@inheritDoc}
*/
public boolean containsValue(final Object value)
{
boolean found = false;
if (null != value)
{
for (final Object v : values)
{
if (value.equals(v))
{
found = true;
break;
}
}
}
return found;
}
/**
* {@inheritDoc}
*/
public V get(final Object key)
{
return get(((Integer)key).intValue());
}
/**
* Overloaded version of {@link Map#get(Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @return the value if found otherwise null
*/
@SuppressWarnings("unchecked")
public V get(final int key)
{
V value = null;
@DoNotSub final int setNumber = Hashing.hash(key, mask);
@DoNotSub final int setBeginIndex = setNumber << setSizeShift;
for (@DoNotSub int i = setBeginIndex, setEndIndex = setBeginIndex + setSize; i < setEndIndex; i++)
{
if (null == values[i])
{
break;
}
if (key == keys[i])
{
value = (V)values[i];
break;
}
}
if (null == value)
{
cacheMisses++;
}
else
{
cacheHits++;
}
return value;
}
/**
* Get a value for a given key, or if it does ot exist then default the value via a
* {@link java.util.function.IntFunction} and put it in the cache.
* <p>
* Primitive specialized version of {@link Map#computeIfAbsent}.
*
* @param key to search on.
* @param mappingFunction to provide a value if the get returns null.
* @return the value if found otherwise the default.
*/
public V computeIfAbsent(final int key, final IntFunction<? extends V> mappingFunction)
{
V value = get(key);
if (value == null)
{
value = mappingFunction.apply(key);
if (value != null)
{
put(key, value);
}
}
return value;
}
/**
* {@inheritDoc}
*/
public V put(final Integer key, final V value)
{
return put(key.intValue(), value);
}
/**
* Overloaded version of {@link Map#put(Object, Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @param value to be inserted in the {@link Map}
* @return always null (as per JCache API, as opposed to {@link Map})
*/
@SuppressWarnings("unchecked")
public V put(final int key, final V value)
{
requireNonNull(value, "null values are not supported");
V evictedValue = null;
@DoNotSub final int setNumber = Hashing.hash(key, mask);
@DoNotSub final int setBeginIndex = setNumber << setSizeShift;
@DoNotSub int i = setBeginIndex;
for (@DoNotSub int nextSetIndex = setBeginIndex + setSize; i < nextSetIndex; i++)
{
if (null == values[i])
{
break;
}
if (key == keys[i])
{
evictedValue = (V)values[i];
shuffleUp(i, nextSetIndex - 1);
break;
}
}
if (null == evictedValue)
{
evictedValue = (V)values[setBeginIndex + (setSize - 1)];
}
shuffleDown(setBeginIndex);
keys[setBeginIndex] = key;
values[setBeginIndex] = value;
cachePuts++;
if (null != evictedValue)
{
evictionConsumer.accept(evictedValue);
}
else
{
++size;
}
return null;
}
/**
* {@inheritDoc}
*/
public V remove(final Object key)
{
return remove(((Integer)key).intValue());
}
/**
* Overloaded version of {@link Map#remove(Object)} that takes a primitive int key.
*
* @param key for indexing the {@link Map}
* @return the value if found otherwise null
*/
@SuppressWarnings("unchecked")
public V remove(final int key)
{
V value = null;
@DoNotSub final int setNumber = Hashing.hash(key, mask);
@DoNotSub final int setBeginIndex = setNumber << setSizeShift;
for (@DoNotSub int i = setBeginIndex, nextSetIndex = setBeginIndex + setSize; i < nextSetIndex; i++)
{
if (null == values[i])
{
break;
}
if (key == keys[i])
{
value = (V)values[i];
shuffleUp(i, nextSetIndex - 1);
--size;
evictionConsumer.accept(value);
break;
}
}
return value;
}
@DoNotSub private void shuffleUp(final int fromIndex, final int toIndex)
{
values[toIndex] = null;
for (@DoNotSub int i = fromIndex; i < toIndex; i++)
{
values[i] = values[i + 1];
keys[i] = keys[i + 1];
}
}
@DoNotSub private void shuffleDown(final int setBeginIndex)
{
for (@DoNotSub int i = setBeginIndex + (setSize - 1); i > setBeginIndex; i--)
{
values[i] = values[i - 1];
keys[i] = keys[i - 1];
}
values[setBeginIndex] = null;
}
/**
* Clear down all items in the cache.
* <p>
* If an exception occurs during the eviction function callback then clear may need to be called again to complete.
* <p>
* If an exception occurs the cache should only be used when {@link #size()} reports zero.
*/
@SuppressWarnings("unchecked")
public void clear()
{
for (@DoNotSub int i = 0, size = values.length; i < size; i++)
{
final Object value = values[i];
if (null != value)
{
values[i] = null;
this.size--;
evictionConsumer.accept((V)value);
}
}
}
/**
* {@inheritDoc}
*/
public void putAll(final Map<? extends Integer, ? extends V> map)
{
for (final Entry<? extends Integer, ? extends V> entry : map.entrySet())
{
put(entry.getKey(), entry.getValue());
}
}
/**
* {@inheritDoc}
*/
public KeySet keySet()
{
if (null == keySet)
{
keySet = new KeySet();
}
return keySet;
}
/**
* {@inheritDoc}
*/
public ValueCollection values()
{
if (null == valueCollection)
{
valueCollection = new ValueCollection();
}
return valueCollection;
}
/**
* {@inheritDoc}
*/
public EntrySet entrySet()
{
if (null == entrySet)
{
entrySet = new EntrySet();
}
return entrySet;
}
/**
* {@inheritDoc}
*/
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append('{');
for (@DoNotSub int i = 0, length = values.length; i < length; i++)
{
final Object value = values[i];
if (null != value)
{
sb.append(keys[i]).append('=').append(value).append(", ");
}
}
if (sb.length() > 1)
{
sb.setLength(sb.length() - 2);
}
sb.append('}');
return sb.toString();
}
/**
* {@inheritDoc}
*/
public boolean equals(final Object o)
{
if (this == o)
{
return true;
}
if (!(o instanceof Map))
{
return false;
}
final Map<?, ?> that = (Map<?, ?>)o;
if (size != that.size())
{
return false;
}
for (@DoNotSub int i = 0, length = values.length; i < length; i++)
{
final Object thisValue = values[i];
if (null != thisValue)
{
final Object thatValue = that.get(keys[i]);
if (!thisValue.equals(thatValue))
{
return false;
}
}
}
return true;
}
/**
* {@inheritDoc}
*/
@DoNotSub public int hashCode()
{
@DoNotSub int result = 0;
for (@DoNotSub int i = 0, length = values.length; i < length; i++)
{
final Object value = values[i];
if (null != value)
{
result += (Integer.hashCode(keys[i]) ^ value.hashCode());
}
}
return result;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Sets and Collections
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* A key set implementation which supports cached iterator to avoid allocation.
*/
public final class KeySet extends AbstractSet<Integer>
{
private final KeyIterator iterator = new KeyIterator();
/**
* {@inheritDoc}
*/
@DoNotSub public int size()
{
return Int2ObjectCache.this.size();
}
/**
* {@inheritDoc}
*/
public boolean contains(final Object o)
{
return Int2ObjectCache.this.containsKey(o);
}
/**
* Check if the given key contained in the set without boxing.
*
* @param key to be checked.
* @return {@code true} if key is contained in the cache.
*/
public boolean contains(final int key)
{
return Int2ObjectCache.this.containsKey(key);
}
/**
* {@inheritDoc}
*/
public KeyIterator iterator()
{
iterator.reset();
return iterator;
}
/**
* {@inheritDoc}
*/
public boolean remove(final Object o)
{
throw new UnsupportedOperationException("Cannot remove on iterator");
}
/**
* {@inheritDoc}
*/
public void clear()
{
Int2ObjectCache.this.clear();
}
}
/**
* Collection of values which supports cached iterator to avoid allocation.
*/
public final class ValueCollection extends AbstractCollection<V>
{
private final ValueIterator iterator = new ValueIterator();
/**
* {@inheritDoc}
*/
@DoNotSub public int size()
{
return Int2ObjectCache.this.size();
}
/**
* {@inheritDoc}
*/
public boolean contains(final Object o)
{
return Int2ObjectCache.this.containsValue(o);
}
/**
* {@inheritDoc}
*/
public ValueIterator iterator()
{
iterator.reset();
return iterator;
}
/**
* {@inheritDoc}
*/
public void clear()
{
Int2ObjectCache.this.clear();
}
}
/**
* Set of entries which supports cached iterator to avoid allocation.
*/
public final class EntrySet extends AbstractSet<Map.Entry<Integer, V>>
{
private final EntryIterator iterator = new EntryIterator();
/**
* {@inheritDoc}
*/
@DoNotSub public int size()
{
return Int2ObjectCache.this.size();
}
/**
* {@inheritDoc}
*/
public EntryIterator iterator()
{
iterator.reset();
return iterator;
}
/**
* {@inheritDoc}
*/
public void clear()
{
Int2ObjectCache.this.clear();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Iterators
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* Base iterator implementation that contains basic logic of traversing the element in the backing array.
*
* @param <T> type of elements.
*/
abstract class AbstractIterator<T> implements Iterator<T>
{
@DoNotSub private int remaining;
@DoNotSub private int position = -1;
/**
* Position of the current element.
*
* @return position of the current element.
*/
@DoNotSub protected final int position()
{
return position;
}
/**
* {@inheritDoc}
*/
public boolean hasNext()
{
return remaining > 0;
}
/**
* Find next element.
*/
protected final void findNext()
{
boolean found = false;
final Object[] values = Int2ObjectCache.this.values;
for (@DoNotSub int i = position + 1; i < capacity; i++)
{
if (null != values[i])
{
found = true;
position = i;
--remaining;
break;
}
}
if (!found)
{
throw new NoSuchElementException();
}
}
/**
* {@inheritDoc}
*/
public abstract T next();
/**
* {@inheritDoc}
*/
public void remove()
{
throw new UnsupportedOperationException("Remove not supported on Iterator");
}
void reset()
{
remaining = size;
position = -1;
}
}
/**
* An iterator over values.
*/
public final class ValueIterator extends AbstractIterator<V>
{
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public V next()
{
findNext();
return (V)values[position()];
}
}
/**
* Iterator over keys which supports access to unboxed keys via {@link #nextInt()}.
*/
public final class KeyIterator extends AbstractIterator<Integer>
{
/**
* {@inheritDoc}
*/
public Integer next()
{
return nextInt();
}
/**
* Return next key without boxing.
*
* @return next key.
*/
public int nextInt()
{
findNext();
return keys[position()];
}
}
/**
* Iterator over entries which supports access to unboxed keys via {@link #getIntKey()}.
*/
public final class EntryIterator
extends AbstractIterator<Entry<Integer, V>>
implements Entry<Integer, V>
{
/**
* {@inheritDoc}
*/
public Entry<Integer, V> next()
{
findNext();
return this;
}
/**
* {@inheritDoc}
*/
public Integer getKey()
{
return getIntKey();
}
/**
* Get key of the current entry.
*
* @return key of the current entry.
*/
public int getIntKey()
{
return keys[position()];
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public V getValue()
{
return (V)values[position()];
}
/**
* {@inheritDoc}
*/
public V setValue(final V value)
{
throw new UnsupportedOperationException("no set on this iterator");
}
}
}