-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClassValue.java
766 lines (690 loc) · 29.7 KB
/
ClassValue.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
package java.lang;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import hobby.wei.c.anno.proguard.Keep;
import scala.compat.classTagDisableCache;
/**
* TODO: 2023/2/18 by Chenakam
* Copy from jdk, and changed some APIs that cannot be called.
* <p>
* Used in {@link scala.reflect.ClassTag$}:
* <pre>
* private val cacheDisabled = java.lang.Boolean.getBoolean("scala.reflect.classtag.cache.disable")
* private[this] object cache extends ClassValue[jWeakReference[ClassTag[_]]]
* </pre>
* But Android's built-in jdk doesn't have this class.
* <p>
* By default, the Android App disables the above {@code cache} using reflection {@link classTagDisableCache}, i.e.
* sets the above `cacheDisabled` to `true`, to invalidate calls to this class.
*
* @see classTagDisableCache
*/
@Keep
public abstract class ClassValue<T> {
// TODO: 2023/2/19
public static boolean isClassTagCacheDisabled = false;
protected ClassValue() {
}
protected abstract T computeValue(Class<?> type);
@Keep
public T get(Class<?> type) {
// TODO: 2023/2/19
if (isClassTagCacheDisabled) return null;
// non-racing this.hashCodeForCache : final int
Entry<?>[] cache;
Entry<T> e = ClassValueMap.probeHomeLocation(cache = getCacheCarefully(type), this);
// racing e : current value <=> stale value from current cache or from stale cache
// invariant: e is null or an Entry with readable Entry.version and Entry.value
if (match(e))
// invariant: No false positive matches. False negatives are OK if rare.
// The key fact that makes this work: if this.version == e.version,
// then this thread has a right to observe (final) e.value.
return e.value();
// The fast path can fail for any of these reasons:
// 1. no entry has been computed yet
// 2. hash code collision (before or after reduction mod cache.length)
// 3. an entry has been removed (either on this type or another)
// 4. the GC has somehow managed to delete e.version and clear the reference
return getFromBackup(cache, type);
}
@Keep
public void remove(Class<?> type) {
// TODO: 2023/2/19
if (isClassTagCacheDisabled) return;
ClassValueMap map = getMap(type);
map.removeEntry(this);
}
// Possible functionality for JSR 292 MR 1
/*public*/ void put(Class<?> type, T value) {
// TODO: 2023/2/19
if (isClassTagCacheDisabled) return;
ClassValueMap map = getMap(type);
map.changeEntry(this, value);
}
/// --------
/// Implementation...
/// --------
/**
* Return the cache, if it exists, else a dummy empty cache.
*/
private static Entry<?>[] getCacheCarefully(Class<?> type) {
// racing type.classValueMap{.cacheArray} : null => new Entry[X] <=> new Entry[Y]
// TODO: 2023/2/18
// ClassValueMap map = type.classValueMap;
// if (map == null) return EMPTY_CACHE;
return EMPTY_CACHE;
// Entry<?>[] cache = map.getCache();
// return cache;
// invariant: returned value is safe to dereference and check for an Entry
}
/**
* Initial, one-element, empty cache used by all Class instances. Must never be filled.
*/
private static final Entry<?>[] EMPTY_CACHE = {null};
/**
* Slow tail of ClassValue.get to retry at nearby locations in the cache,
* or take a slow lock and check the hash table.
* Called only if the first probe was empty or a collision.
* This is a separate method, so compilers can process it independently.
*/
private T getFromBackup(Entry<?>[] cache, Class<?> type) {
Entry<T> e = ClassValueMap.probeBackupLocations(cache, this);
if (e != null) return e.value();
return getFromHashMap(type);
}
// Hack to suppress warnings on the (T) cast, which is a no-op.
@SuppressWarnings("unchecked")
Entry<T> castEntry(Entry<?> e) {
return (Entry<T>) e;
}
/**
* Called when the fast path of get fails, and cache reprobe also fails.
*/
private T getFromHashMap(Class<?> type) {
// The fail-safe recovery is to fall back to the underlying classValueMap.
ClassValueMap map = getMap(type);
for (; ; ) {
Entry<T> e = map.startEntry(this);
if (!e.isPromise()) return e.value();
try {
// Try to make a real entry for the promised version.
e = makeEntry(e.version(), computeValue(type));
} finally {
// Whether computeValue throws or returns normally,
// be sure to remove the empty entry.
e = map.finishEntry(this, e);
}
if (e != null) return e.value();
// else try again, in case a racing thread called remove (so e == null)
}
}
/**
* Check that e is non-null, matches this ClassValue, and is live.
*/
boolean match(Entry<?> e) {
// racing e.version : null (blank) => unique Version token => null (GC-ed version)
// non-racing this.version : v1 => v2 => ... (updates are read faithfully from volatile)
return (e != null && e.get() == this.version);
// invariant: No false positives on version match. Null is OK for false negative.
// invariant: If version matches, then e.value is readable (final set in Entry.<init>)
}
/**
* Internal hash code for accessing Class.classValueMap.cacheArray.
*/
final int hashCodeForCache = nextHashCode.getAndAdd(HASH_INCREMENT) & HASH_MASK;
/**
* Value stream for hashCodeForCache. See similar structure in ThreadLocal.
*/
private static final AtomicInteger nextHashCode = new AtomicInteger();
/**
* Good for power-of-two tables. See similar structure in ThreadLocal.
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Mask a hash code to be positive but not too large, to prevent wraparound.
*/
static final int HASH_MASK = (-1 >>> 2);
/**
* Private key for retrieval of this object from ClassValueMap.
*/
static class Identity {
}
/**
* This ClassValue's identity, expressed as an opaque object.
* The main object {@code ClassValue.this} is incorrect since
* subclasses may override {@code ClassValue.equals}, which
* could confuse keys in the ClassValueMap.
*/
final Identity identity = new Identity();
/**
* Current version for retrieving this class value from the cache.
* Any number of computeValue calls can be cached in association with one version.
* But the version changes when a remove (on any type) is executed.
* A version change invalidates all cache entries for the affected ClassValue,
* by marking them as stale. Stale cache entries do not force another call
* to computeValue, but they do require a synchronized visit to a backing map.
* <p>
* All user-visible state changes on the ClassValue take place under
* a lock inside the synchronized methods of ClassValueMap.
* Readers (of ClassValue.get) are notified of such state changes
* when this.version is bumped to a new token.
* This variable must be volatile so that an unsynchronized reader
* will receive the notification without delay.
* <p>
* If version were not volatile, one thread T1 could persistently hold onto
* a stale value this.value == V1, while another thread T2 advances
* (under a lock) to this.value == V2. This will typically be harmless,
* but if T1 and T2 interact causally via some other channel, such that
* T1's further actions are constrained (in the JMM) to happen after
* the V2 event, then T1's observation of V1 will be an error.
* <p>
* The practical effect of making this.version be volatile is that it cannot
* be hoisted out of a loop (by an optimizing JIT) or otherwise cached.
* Some machines may also require a barrier instruction to execute
* before this.version.
*/
private volatile Version<T> version = new Version<>(this);
Version<T> version() {
return version;
}
void bumpVersion() {
version = new Version<>(this);
}
static class Version<T> {
private final ClassValue<T> classValue;
private final Entry<T> promise = new Entry<>(this);
Version(ClassValue<T> classValue) {
this.classValue = classValue;
}
ClassValue<T> classValue() {
return classValue;
}
Entry<T> promise() {
return promise;
}
boolean isLive() {
return classValue.version() == this;
}
}
/**
* One binding of a value to a class via a ClassValue.
* States are:<ul>
* <li> promise if value == Entry.this
* <li> else dead if version == null
* <li> else stale if version != classValue.version
* <li> else live </ul>
* Promises are never put into the cache; they only live in the
* backing map while a computeValue call is in flight.
* Once an entry goes stale, it can be reset at any time
* into the dead state.
*/
static class Entry<T> extends WeakReference<Version<T>> {
final Object value; // usually of type T, but sometimes (Entry)this
Entry(Version<T> version, T value) {
super(version);
this.value = value; // for a regular entry, value is of type T
}
private void assertNotPromise() {
assert (!isPromise());
}
/**
* For creating a promise.
*/
Entry(Version<T> version) {
super(version);
this.value = this; // for a promise, value is not of type T, but Entry!
}
/**
* Fetch the value. This entry must not be a promise.
*/
@SuppressWarnings("unchecked")
// if !isPromise, type is T
T value() {
assertNotPromise();
return (T) value;
}
boolean isPromise() {
return value == this;
}
Version<T> version() {
return get();
}
ClassValue<T> classValueOrNull() {
Version<T> v = version();
return (v == null) ? null : v.classValue();
}
boolean isLive() {
Version<T> v = version();
if (v == null) return false;
if (v.isLive()) return true;
clear();
return false;
}
Entry<T> refreshVersion(Version<T> v2) {
assertNotPromise();
@SuppressWarnings("unchecked") // if !isPromise, type is T
Entry<T> e2 = new Entry<>(v2, (T) value);
clear();
// value = null -- caller must drop
return e2;
}
static final Entry<?> DEAD_ENTRY = new Entry<>(null, null);
}
/**
* Return the backing map associated with this type.
*/
private static ClassValueMap getMap(Class<?> type) {
// racing type.classValueMap : null (blank) => unique ClassValueMap
// if a null is observed, a map is created (lazily, synchronously, uniquely)
// all further access to that map is synchronized
// TODO: 2023/2/18
// ClassValueMap map = type.classValueMap;
ClassValueMap map = weakHashMap.get(type);
if (map != null) return map;
return initializeMap(type);
}
private static final Object CRITICAL_SECTION = new Object();
// private static final Unsafe UNSAFE = Unsafe.getUnsafe();
// TODO: 2023/2/18
private static final WeakHashMap<Class<?>, ClassValueMap> weakHashMap = new WeakHashMap<>();
private static ClassValueMap initializeMap(Class<?> type) {
ClassValueMap map;
synchronized (CRITICAL_SECTION) { // private object to avoid deadlocks
// happens about once per type
// TODO: 2023/2/18
// if ((map = type.classValueMap) == null) {
// map = new ClassValueMap();
// // Place a Store fence after construction and before publishing to emulate
// // ClassValueMap containing final fields. This ensures it can be
// // published safely in the non-volatile field Class.classValueMap,
// // since stores to the fields of ClassValueMap will not be reordered
// // to occur after the store to the field type.classValueMap
// UNSAFE.storeFence();
//
// type.classValueMap = map;
// }
if ((map = weakHashMap.get(type)) == null) {
map = new ClassValueMap();
weakHashMap.put(type, map);
}
}
return map;
}
static <T> Entry<T> makeEntry(Version<T> explicitVersion, T value) {
// Note that explicitVersion might be different from this.version.
return new Entry<>(explicitVersion, value);
// As soon as the Entry is put into the cache, the value will be
// reachable via a data race (as defined by the Java Memory Model).
// This race is benign, assuming the value object itself can be
// read safely by multiple threads. This is up to the user.
//
// The entry and version fields themselves can be safely read via
// a race because they are either final or have controlled states.
// If the pointer from the entry to the version is still null,
// or if the version goes immediately dead and is nulled out,
// the reader will take the slow path and retry under a lock.
}
// The following class could also be top level and non-public:
/**
* A backing map for all ClassValues.
* Gives a fully serialized "true state" for each pair (ClassValue cv, Class type).
* Also manages an unserialized fast-path cache.
*/
static class ClassValueMap extends WeakHashMap<Identity, Entry<?>> {
private ClassValue.Entry<?>[] cacheArray;
private int cacheLoad, cacheLoadLimit;
/**
* Number of entries initially allocated to each type when first used with any ClassValue.
* It would be pointless to make this much smaller than the Class and ClassValueMap objects themselves.
* Must be a power of 2.
*/
private static final int INITIAL_ENTRIES = 32;
/**
* Build a backing map for ClassValues.
* Also, create an empty cache array and install it on the class.
*/
ClassValueMap() {
sizeCache(INITIAL_ENTRIES);
}
ClassValue.Entry<?>[] getCache() {
return cacheArray;
}
/**
* Initiate a query. Store a promise (placeholder) if there is no value yet.
*/
synchronized <T> ClassValue.Entry<T> startEntry(ClassValue<T> classValue) {
@SuppressWarnings("unchecked") // one map has entries for all value types <T>
ClassValue.Entry<T> e = (ClassValue.Entry<T>) get(classValue.identity);
Version<T> v = classValue.version();
if (e == null) {
e = v.promise();
// The presence of a promise means that a value is pending for v.
// Eventually, finishEntry will overwrite the promise.
put(classValue.identity, e);
// Note that the promise is never entered into the cache!
return e;
} else if (e.isPromise()) {
// Somebody else has asked the same question.
// Let the races begin!
if (e.version() != v) {
e = v.promise();
put(classValue.identity, e);
}
return e;
} else {
// there is already a completed entry here; report it
if (e.version() != v) {
// There is a stale but valid entry here; make it fresh again.
// Once an entry is in the hash table, we don't care what its version is.
e = e.refreshVersion(v);
put(classValue.identity, e);
}
// Add to the cache, to enable the fast path, next time.
checkCacheLoad();
addToCache(classValue, e);
return e;
}
}
/**
* Finish a query. Overwrite a matching placeholder. Drop stale incoming values.
*/
synchronized <T> ClassValue.Entry<T> finishEntry(ClassValue<T> classValue, ClassValue.Entry<T> e) {
@SuppressWarnings("unchecked") // one map has entries for all value types <T>
ClassValue.Entry<T> e0 = (ClassValue.Entry<T>) get(classValue.identity);
if (e == e0) {
// We can get here during exception processing, unwinding from computeValue.
assert (e.isPromise());
remove(classValue.identity);
return null;
} else if (e0 != null && e0.isPromise() && e0.version() == e.version()) {
// If e0 matches the intended entry, there has not been a remove call
// between the previous startEntry and now. So now overwrite e0.
Version<T> v = classValue.version();
if (e.version() != v) e = e.refreshVersion(v);
put(classValue.identity, e);
// Add to the cache, to enable the fast path, next time.
checkCacheLoad();
addToCache(classValue, e);
return e;
} else {
// Some sort of mismatch; caller must try again.
return null;
}
}
/**
* Remove an entry.
*/
synchronized void removeEntry(ClassValue<?> classValue) {
ClassValue.Entry<?> e = remove(classValue.identity);
if (e == null) {
// Uninitialized, and no pending calls to computeValue. No change.
} else if (e.isPromise()) {
// State is uninitialized, with a pending call to finishEntry.
// Since remove is a no-op in such a state, keep the promise
// by putting it back into the map.
put(classValue.identity, e);
} else {
// In an initialized state. Bump forward, and de-initialize.
classValue.bumpVersion();
// Make all cache elements for this guy go stale.
removeStaleEntries(classValue);
}
}
/**
* Change the value for an entry.
*/
synchronized <T> void changeEntry(ClassValue<T> classValue, T value) {
@SuppressWarnings("unchecked") // one map has entries for all value types <T>
ClassValue.Entry<T> e0 = (ClassValue.Entry<T>) get(classValue.identity);
Version<T> version = classValue.version();
if (e0 != null) {
if (e0.version() == version && e0.value() == value)
// no value change => no version change needed
return;
classValue.bumpVersion();
removeStaleEntries(classValue);
}
ClassValue.Entry<T> e = makeEntry(version, value);
put(classValue.identity, e);
// Add to the cache, to enable the fast path, next time.
checkCacheLoad();
addToCache(classValue, e);
}
/// --------
/// Cache management.
/// --------
// Statics do not need synchronization.
/**
* Load the cache entry at the given (hashed) location.
*/
static ClassValue.Entry<?> loadFromCache(ClassValue.Entry<?>[] cache, int i) {
// non-racing cache.length : constant
// racing cache[i & (mask)] : null <=> Entry
return cache[i & (cache.length - 1)];
// invariant: returned value is null or well-constructed (ready to match)
}
/**
* Look in the cache, at the home location for the given ClassValue.
*/
static <T> ClassValue.Entry<T> probeHomeLocation(ClassValue.Entry<?>[] cache, ClassValue<T> classValue) {
return classValue.castEntry(loadFromCache(cache, classValue.hashCodeForCache));
}
/**
* Given that first probe was a collision, retry at nearby locations.
*/
static <T> ClassValue.Entry<T> probeBackupLocations(ClassValue.Entry<?>[] cache, ClassValue<T> classValue) {
if (PROBE_LIMIT <= 0) return null;
// Probe the cache carefully, in a range of slots.
int mask = (cache.length - 1);
int home = (classValue.hashCodeForCache & mask);
ClassValue.Entry<?> e2 = cache[home]; // victim, if we find the real guy
if (e2 == null) {
return null; // if nobody is at home, no need to search nearby
}
// assume !classValue.match(e2), but do not assert, because of races
int pos2 = -1;
for (int i = home + 1; i < home + PROBE_LIMIT; i++) {
ClassValue.Entry<?> e = cache[i & mask];
if (e == null) {
break; // only search within non-null runs
}
if (classValue.match(e)) {
// relocate colliding entry e2 (from cache[home]) to first empty slot
cache[home] = e;
if (pos2 >= 0) {
cache[i & mask] = ClassValue.Entry.DEAD_ENTRY;
} else {
pos2 = i;
}
cache[pos2 & mask] = ((entryDislocation(cache, pos2, e2) < PROBE_LIMIT) ? e2 // put e2 here if it fits
: ClassValue.Entry.DEAD_ENTRY);
return classValue.castEntry(e);
}
// Remember first empty slot, if any:
if (!e.isLive() && pos2 < 0) pos2 = i;
}
return null;
}
/**
* How far out of place is e?
*/
private static int entryDislocation(ClassValue.Entry<?>[] cache, int pos, ClassValue.Entry<?> e) {
ClassValue<?> cv = e.classValueOrNull();
if (cv == null) return 0; // entry is not live!
int mask = (cache.length - 1);
return (pos - cv.hashCodeForCache) & mask;
}
/// --------
/// Below this line all functions are private, and assume synchronized access.
/// --------
private void sizeCache(int length) {
assert ((length & (length - 1)) == 0); // must be power of 2
cacheLoad = 0;
cacheLoadLimit = (int) ((double) length * CACHE_LOAD_LIMIT / 100);
cacheArray = new ClassValue.Entry<?>[length];
}
/**
* Make sure the cache load stays below its limit, if possible.
*/
private void checkCacheLoad() {
if (cacheLoad >= cacheLoadLimit) {
reduceCacheLoad();
}
}
private void reduceCacheLoad() {
removeStaleEntries();
if (cacheLoad < cacheLoadLimit) return; // win
ClassValue.Entry<?>[] oldCache = getCache();
if (oldCache.length > HASH_MASK) return; // lose
sizeCache(oldCache.length * 2);
for (ClassValue.Entry<?> e : oldCache) {
if (e != null && e.isLive()) {
addToCache(e);
}
}
}
/**
* Remove stale entries in the given range.
* Should be executed under a Map lock.
*/
private void removeStaleEntries(ClassValue.Entry<?>[] cache, int begin, int count) {
if (PROBE_LIMIT <= 0) return;
int mask = (cache.length - 1);
int removed = 0;
for (int i = begin; i < begin + count; i++) {
ClassValue.Entry<?> e = cache[i & mask];
if (e == null || e.isLive()) continue; // skip null and live entries
ClassValue.Entry<?> replacement = null;
if (PROBE_LIMIT > 1) {
// avoid breaking up a non-null run
replacement = findReplacement(cache, i);
}
cache[i & mask] = replacement;
if (replacement == null) removed += 1;
}
cacheLoad = Math.max(0, cacheLoad - removed);
}
/**
* Clearing a cache slot risks disconnecting following entries
* from the head of a non-null run, which would allow them
* to be found via reprobes. Find an entry after cache[begin]
* to plug into the hole, or return null if none is needed.
*/
private ClassValue.Entry<?> findReplacement(ClassValue.Entry<?>[] cache, int home1) {
ClassValue.Entry<?> replacement = null;
int haveReplacement = -1, replacementPos = 0;
int mask = (cache.length - 1);
for (int i2 = home1 + 1; i2 < home1 + PROBE_LIMIT; i2++) {
ClassValue.Entry<?> e2 = cache[i2 & mask];
if (e2 == null) break; // End of non-null run.
if (!e2.isLive()) continue; // Doomed anyway.
int dis2 = entryDislocation(cache, i2, e2);
if (dis2 == 0) continue; // e2 already optimally placed
int home2 = i2 - dis2;
if (home2 <= home1) {
// e2 can replace entry at cache[home1]
if (home2 == home1) {
// Put e2 exactly where he belongs.
haveReplacement = 1;
replacementPos = i2;
replacement = e2;
} else if (haveReplacement <= 0) {
haveReplacement = 0;
replacementPos = i2;
replacement = e2;
}
// And keep going, so we can favor larger dislocations.
}
}
if (haveReplacement >= 0) {
if (cache[(replacementPos + 1) & mask] != null) {
// Be conservative, to avoid breaking up a non-null run.
cache[replacementPos & mask] = (ClassValue.Entry<?>) ClassValue.Entry.DEAD_ENTRY;
} else {
cache[replacementPos & mask] = null;
cacheLoad -= 1;
}
}
return replacement;
}
/**
* Remove stale entries in the range near classValue.
*/
private void removeStaleEntries(ClassValue<?> classValue) {
removeStaleEntries(getCache(), classValue.hashCodeForCache, PROBE_LIMIT);
}
/**
* Remove all stale entries, everywhere.
*/
private void removeStaleEntries() {
ClassValue.Entry<?>[] cache = getCache();
removeStaleEntries(cache, 0, cache.length + PROBE_LIMIT - 1);
}
/**
* Add the given entry to the cache, in its home location, unless it is out of date.
*/
private <T> void addToCache(ClassValue.Entry<T> e) {
ClassValue<T> classValue = e.classValueOrNull();
if (classValue != null) addToCache(classValue, e);
}
/**
* Add the given entry to the cache, in its home location.
*/
private <T> void addToCache(ClassValue<T> classValue, ClassValue.Entry<T> e) {
if (PROBE_LIMIT <= 0) return; // do not fill cache
// Add e to the cache.
ClassValue.Entry<?>[] cache = getCache();
int mask = (cache.length - 1);
int home = classValue.hashCodeForCache & mask;
ClassValue.Entry<?> e2 = placeInCache(cache, home, e, false);
if (e2 == null) return; // done
if (PROBE_LIMIT > 1) {
// try to move e2 somewhere else in his probe range
int dis2 = entryDislocation(cache, home, e2);
int home2 = home - dis2;
for (int i2 = home2; i2 < home2 + PROBE_LIMIT; i2++) {
if (placeInCache(cache, i2 & mask, e2, true) == null) {
return;
}
}
}
// Note: At this point, e2 is just dropped from the cache.
}
/**
* Store the given entry. Update cacheLoad, and return any live victim.
* 'Gently' means return self rather than dislocating a live victim.
*/
private ClassValue.Entry<?> placeInCache(ClassValue.Entry<?>[] cache, int pos, ClassValue.Entry<?> e, boolean gently) {
ClassValue.Entry<?> e2 = overwrittenEntry(cache[pos]);
if (gently && e2 != null) {
// do not overwrite a live entry
return e;
} else {
cache[pos] = e;
return e2;
}
}
/**
* Note an entry that is about to be overwritten.
* If it is not live, quietly replace it by null.
* If it is an actual null, increment cacheLoad,
* because the caller is going to store something
* in its place.
*/
private <T> ClassValue.Entry<T> overwrittenEntry(ClassValue.Entry<T> e2) {
if (e2 == null) cacheLoad += 1;
else if (e2.isLive()) return e2;
return null;
}
/**
* Percent loading of cache before resize.
*/
private static final int CACHE_LOAD_LIMIT = 67; // 0..100
/**
* Maximum number of probes to attempt.
*/
private static final int PROBE_LIMIT = 6; // 1..
// N.B. Set PROBE_LIMIT=0 to disable all fast paths.
}
}