Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/lang/ClassValue.java
38829 views
1
/*
2
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.lang;
27
28
import java.lang.ClassValue.ClassValueMap;
29
import java.util.WeakHashMap;
30
import java.lang.ref.WeakReference;
31
import java.util.concurrent.atomic.AtomicInteger;
32
33
import sun.misc.Unsafe;
34
35
import static java.lang.ClassValue.ClassValueMap.probeHomeLocation;
36
import static java.lang.ClassValue.ClassValueMap.probeBackupLocations;
37
38
/**
39
* Lazily associate a computed value with (potentially) every type.
40
* For example, if a dynamic language needs to construct a message dispatch
41
* table for each class encountered at a message send call site,
42
* it can use a {@code ClassValue} to cache information needed to
43
* perform the message send quickly, for each class encountered.
44
* @author John Rose, JSR 292 EG
45
* @since 1.7
46
*/
47
public abstract class ClassValue<T> {
48
/**
49
* Sole constructor. (For invocation by subclass constructors, typically
50
* implicit.)
51
*/
52
protected ClassValue() {
53
}
54
55
/**
56
* Computes the given class's derived value for this {@code ClassValue}.
57
* <p>
58
* This method will be invoked within the first thread that accesses
59
* the value with the {@link #get get} method.
60
* <p>
61
* Normally, this method is invoked at most once per class,
62
* but it may be invoked again if there has been a call to
63
* {@link #remove remove}.
64
* <p>
65
* If this method throws an exception, the corresponding call to {@code get}
66
* will terminate abnormally with that exception, and no class value will be recorded.
67
*
68
* @param type the type whose class value must be computed
69
* @return the newly computed value associated with this {@code ClassValue}, for the given class or interface
70
* @see #get
71
* @see #remove
72
*/
73
protected abstract T computeValue(Class<?> type);
74
75
/**
76
* Returns the value for the given class.
77
* If no value has yet been computed, it is obtained by
78
* an invocation of the {@link #computeValue computeValue} method.
79
* <p>
80
* The actual installation of the value on the class
81
* is performed atomically.
82
* At that point, if several racing threads have
83
* computed values, one is chosen, and returned to
84
* all the racing threads.
85
* <p>
86
* The {@code type} parameter is typically a class, but it may be any type,
87
* such as an interface, a primitive type (like {@code int.class}), or {@code void.class}.
88
* <p>
89
* In the absence of {@code remove} calls, a class value has a simple
90
* state diagram: uninitialized and initialized.
91
* When {@code remove} calls are made,
92
* the rules for value observation are more complex.
93
* See the documentation for {@link #remove remove} for more information.
94
*
95
* @param type the type whose class value must be computed or retrieved
96
* @return the current value associated with this {@code ClassValue}, for the given class or interface
97
* @throws NullPointerException if the argument is null
98
* @see #remove
99
* @see #computeValue
100
*/
101
public T get(Class<?> type) {
102
// non-racing this.hashCodeForCache : final int
103
Entry<?>[] cache;
104
Entry<T> e = probeHomeLocation(cache = getCacheCarefully(type), this);
105
// racing e : current value <=> stale value from current cache or from stale cache
106
// invariant: e is null or an Entry with readable Entry.version and Entry.value
107
if (match(e))
108
// invariant: No false positive matches. False negatives are OK if rare.
109
// The key fact that makes this work: if this.version == e.version,
110
// then this thread has a right to observe (final) e.value.
111
return e.value();
112
// The fast path can fail for any of these reasons:
113
// 1. no entry has been computed yet
114
// 2. hash code collision (before or after reduction mod cache.length)
115
// 3. an entry has been removed (either on this type or another)
116
// 4. the GC has somehow managed to delete e.version and clear the reference
117
return getFromBackup(cache, type);
118
}
119
120
/**
121
* Removes the associated value for the given class.
122
* If this value is subsequently {@linkplain #get read} for the same class,
123
* its value will be reinitialized by invoking its {@link #computeValue computeValue} method.
124
* This may result in an additional invocation of the
125
* {@code computeValue} method for the given class.
126
* <p>
127
* In order to explain the interaction between {@code get} and {@code remove} calls,
128
* we must model the state transitions of a class value to take into account
129
* the alternation between uninitialized and initialized states.
130
* To do this, number these states sequentially from zero, and note that
131
* uninitialized (or removed) states are numbered with even numbers,
132
* while initialized (or re-initialized) states have odd numbers.
133
* <p>
134
* When a thread {@code T} removes a class value in state {@code 2N},
135
* nothing happens, since the class value is already uninitialized.
136
* Otherwise, the state is advanced atomically to {@code 2N+1}.
137
* <p>
138
* When a thread {@code T} queries a class value in state {@code 2N},
139
* the thread first attempts to initialize the class value to state {@code 2N+1}
140
* by invoking {@code computeValue} and installing the resulting value.
141
* <p>
142
* When {@code T} attempts to install the newly computed value,
143
* if the state is still at {@code 2N}, the class value will be initialized
144
* with the computed value, advancing it to state {@code 2N+1}.
145
* <p>
146
* Otherwise, whether the new state is even or odd,
147
* {@code T} will discard the newly computed value
148
* and retry the {@code get} operation.
149
* <p>
150
* Discarding and retrying is an important proviso,
151
* since otherwise {@code T} could potentially install
152
* a disastrously stale value. For example:
153
* <ul>
154
* <li>{@code T} calls {@code CV.get(C)} and sees state {@code 2N}
155
* <li>{@code T} quickly computes a time-dependent value {@code V0} and gets ready to install it
156
* <li>{@code T} is hit by an unlucky paging or scheduling event, and goes to sleep for a long time
157
* <li>...meanwhile, {@code T2} also calls {@code CV.get(C)} and sees state {@code 2N}
158
* <li>{@code T2} quickly computes a similar time-dependent value {@code V1} and installs it on {@code CV.get(C)}
159
* <li>{@code T2} (or a third thread) then calls {@code CV.remove(C)}, undoing {@code T2}'s work
160
* <li> the previous actions of {@code T2} are repeated several times
161
* <li> also, the relevant computed values change over time: {@code V1}, {@code V2}, ...
162
* <li>...meanwhile, {@code T} wakes up and attempts to install {@code V0}; <em>this must fail</em>
163
* </ul>
164
* We can assume in the above scenario that {@code CV.computeValue} uses locks to properly
165
* observe the time-dependent states as it computes {@code V1}, etc.
166
* This does not remove the threat of a stale value, since there is a window of time
167
* between the return of {@code computeValue} in {@code T} and the installation
168
* of the the new value. No user synchronization is possible during this time.
169
*
170
* @param type the type whose class value must be removed
171
* @throws NullPointerException if the argument is null
172
*/
173
public void remove(Class<?> type) {
174
ClassValueMap map = getMap(type);
175
map.removeEntry(this);
176
}
177
178
// Possible functionality for JSR 292 MR 1
179
/*public*/ void put(Class<?> type, T value) {
180
ClassValueMap map = getMap(type);
181
map.changeEntry(this, value);
182
}
183
184
/// --------
185
/// Implementation...
186
/// --------
187
188
/** Return the cache, if it exists, else a dummy empty cache. */
189
private static Entry<?>[] getCacheCarefully(Class<?> type) {
190
// racing type.classValueMap{.cacheArray} : null => new Entry[X] <=> new Entry[Y]
191
ClassValueMap map = type.classValueMap;
192
if (map == null) return EMPTY_CACHE;
193
Entry<?>[] cache = map.getCache();
194
return cache;
195
// invariant: returned value is safe to dereference and check for an Entry
196
}
197
198
/** Initial, one-element, empty cache used by all Class instances. Must never be filled. */
199
private static final Entry<?>[] EMPTY_CACHE = { null };
200
201
/**
202
* Slow tail of ClassValue.get to retry at nearby locations in the cache,
203
* or take a slow lock and check the hash table.
204
* Called only if the first probe was empty or a collision.
205
* This is a separate method, so compilers can process it independently.
206
*/
207
private T getFromBackup(Entry<?>[] cache, Class<?> type) {
208
Entry<T> e = probeBackupLocations(cache, this);
209
if (e != null)
210
return e.value();
211
return getFromHashMap(type);
212
}
213
214
// Hack to suppress warnings on the (T) cast, which is a no-op.
215
@SuppressWarnings("unchecked")
216
Entry<T> castEntry(Entry<?> e) { return (Entry<T>) e; }
217
218
/** Called when the fast path of get fails, and cache reprobe also fails.
219
*/
220
private T getFromHashMap(Class<?> type) {
221
// The fail-safe recovery is to fall back to the underlying classValueMap.
222
ClassValueMap map = getMap(type);
223
for (;;) {
224
Entry<T> e = map.startEntry(this);
225
if (!e.isPromise())
226
return e.value();
227
try {
228
// Try to make a real entry for the promised version.
229
e = makeEntry(e.version(), computeValue(type));
230
} finally {
231
// Whether computeValue throws or returns normally,
232
// be sure to remove the empty entry.
233
e = map.finishEntry(this, e);
234
}
235
if (e != null)
236
return e.value();
237
// else try again, in case a racing thread called remove (so e == null)
238
}
239
}
240
241
/** Check that e is non-null, matches this ClassValue, and is live. */
242
boolean match(Entry<?> e) {
243
// racing e.version : null (blank) => unique Version token => null (GC-ed version)
244
// non-racing this.version : v1 => v2 => ... (updates are read faithfully from volatile)
245
return (e != null && e.get() == this.version);
246
// invariant: No false positives on version match. Null is OK for false negative.
247
// invariant: If version matches, then e.value is readable (final set in Entry.<init>)
248
}
249
250
/** Internal hash code for accessing Class.classValueMap.cacheArray. */
251
final int hashCodeForCache = nextHashCode.getAndAdd(HASH_INCREMENT) & HASH_MASK;
252
253
/** Value stream for hashCodeForCache. See similar structure in ThreadLocal. */
254
private static final AtomicInteger nextHashCode = new AtomicInteger();
255
256
/** Good for power-of-two tables. See similar structure in ThreadLocal. */
257
private static final int HASH_INCREMENT = 0x61c88647;
258
259
/** Mask a hash code to be positive but not too large, to prevent wraparound. */
260
static final int HASH_MASK = (-1 >>> 2);
261
262
/**
263
* Private key for retrieval of this object from ClassValueMap.
264
*/
265
static class Identity {
266
}
267
/**
268
* This ClassValue's identity, expressed as an opaque object.
269
* The main object {@code ClassValue.this} is incorrect since
270
* subclasses may override {@code ClassValue.equals}, which
271
* could confuse keys in the ClassValueMap.
272
*/
273
final Identity identity = new Identity();
274
275
/**
276
* Current version for retrieving this class value from the cache.
277
* Any number of computeValue calls can be cached in association with one version.
278
* But the version changes when a remove (on any type) is executed.
279
* A version change invalidates all cache entries for the affected ClassValue,
280
* by marking them as stale. Stale cache entries do not force another call
281
* to computeValue, but they do require a synchronized visit to a backing map.
282
* <p>
283
* All user-visible state changes on the ClassValue take place under
284
* a lock inside the synchronized methods of ClassValueMap.
285
* Readers (of ClassValue.get) are notified of such state changes
286
* when this.version is bumped to a new token.
287
* This variable must be volatile so that an unsynchronized reader
288
* will receive the notification without delay.
289
* <p>
290
* If version were not volatile, one thread T1 could persistently hold onto
291
* a stale value this.value == V1, while while another thread T2 advances
292
* (under a lock) to this.value == V2. This will typically be harmless,
293
* but if T1 and T2 interact causally via some other channel, such that
294
* T1's further actions are constrained (in the JMM) to happen after
295
* the V2 event, then T1's observation of V1 will be an error.
296
* <p>
297
* The practical effect of making this.version be volatile is that it cannot
298
* be hoisted out of a loop (by an optimizing JIT) or otherwise cached.
299
* Some machines may also require a barrier instruction to execute
300
* before this.version.
301
*/
302
private volatile Version<T> version = new Version<>(this);
303
Version<T> version() { return version; }
304
void bumpVersion() { version = new Version<>(this); }
305
static class Version<T> {
306
private final ClassValue<T> classValue;
307
private final Entry<T> promise = new Entry<>(this);
308
Version(ClassValue<T> classValue) { this.classValue = classValue; }
309
ClassValue<T> classValue() { return classValue; }
310
Entry<T> promise() { return promise; }
311
boolean isLive() { return classValue.version() == this; }
312
}
313
314
/** One binding of a value to a class via a ClassValue.
315
* States are:<ul>
316
* <li> promise if value == Entry.this
317
* <li> else dead if version == null
318
* <li> else stale if version != classValue.version
319
* <li> else live </ul>
320
* Promises are never put into the cache; they only live in the
321
* backing map while a computeValue call is in flight.
322
* Once an entry goes stale, it can be reset at any time
323
* into the dead state.
324
*/
325
static class Entry<T> extends WeakReference<Version<T>> {
326
final Object value; // usually of type T, but sometimes (Entry)this
327
Entry(Version<T> version, T value) {
328
super(version);
329
this.value = value; // for a regular entry, value is of type T
330
}
331
private void assertNotPromise() { assert(!isPromise()); }
332
/** For creating a promise. */
333
Entry(Version<T> version) {
334
super(version);
335
this.value = this; // for a promise, value is not of type T, but Entry!
336
}
337
/** Fetch the value. This entry must not be a promise. */
338
@SuppressWarnings("unchecked") // if !isPromise, type is T
339
T value() { assertNotPromise(); return (T) value; }
340
boolean isPromise() { return value == this; }
341
Version<T> version() { return get(); }
342
ClassValue<T> classValueOrNull() {
343
Version<T> v = version();
344
return (v == null) ? null : v.classValue();
345
}
346
boolean isLive() {
347
Version<T> v = version();
348
if (v == null) return false;
349
if (v.isLive()) return true;
350
clear();
351
return false;
352
}
353
Entry<T> refreshVersion(Version<T> v2) {
354
assertNotPromise();
355
@SuppressWarnings("unchecked") // if !isPromise, type is T
356
Entry<T> e2 = new Entry<>(v2, (T) value);
357
clear();
358
// value = null -- caller must drop
359
return e2;
360
}
361
static final Entry<?> DEAD_ENTRY = new Entry<>(null, null);
362
}
363
364
/** Return the backing map associated with this type. */
365
private static ClassValueMap getMap(Class<?> type) {
366
// racing type.classValueMap : null (blank) => unique ClassValueMap
367
// if a null is observed, a map is created (lazily, synchronously, uniquely)
368
// all further access to that map is synchronized
369
ClassValueMap map = type.classValueMap;
370
if (map != null) return map;
371
return initializeMap(type);
372
}
373
374
private static final Object CRITICAL_SECTION = new Object();
375
private static final Unsafe UNSAFE = Unsafe.getUnsafe();
376
private static ClassValueMap initializeMap(Class<?> type) {
377
ClassValueMap map;
378
synchronized (CRITICAL_SECTION) { // private object to avoid deadlocks
379
// happens about once per type
380
if ((map = type.classValueMap) == null) {
381
map = new ClassValueMap(type);
382
// Place a Store fence after construction and before publishing to emulate
383
// ClassValueMap containing final fields. This ensures it can be
384
// published safely in the non-volatile field Class.classValueMap,
385
// since stores to the fields of ClassValueMap will not be reordered
386
// to occur after the store to the field type.classValueMap
387
UNSAFE.storeFence();
388
389
type.classValueMap = map;
390
}
391
}
392
return map;
393
}
394
395
static <T> Entry<T> makeEntry(Version<T> explicitVersion, T value) {
396
// Note that explicitVersion might be different from this.version.
397
return new Entry<>(explicitVersion, value);
398
399
// As soon as the Entry is put into the cache, the value will be
400
// reachable via a data race (as defined by the Java Memory Model).
401
// This race is benign, assuming the value object itself can be
402
// read safely by multiple threads. This is up to the user.
403
//
404
// The entry and version fields themselves can be safely read via
405
// a race because they are either final or have controlled states.
406
// If the pointer from the entry to the version is still null,
407
// or if the version goes immediately dead and is nulled out,
408
// the reader will take the slow path and retry under a lock.
409
}
410
411
// The following class could also be top level and non-public:
412
413
/** A backing map for all ClassValues, relative a single given type.
414
* Gives a fully serialized "true state" for each pair (ClassValue cv, Class type).
415
* Also manages an unserialized fast-path cache.
416
*/
417
static class ClassValueMap extends WeakHashMap<ClassValue.Identity, Entry<?>> {
418
private final Class<?> type;
419
private Entry<?>[] cacheArray;
420
private int cacheLoad, cacheLoadLimit;
421
422
/** Number of entries initially allocated to each type when first used with any ClassValue.
423
* It would be pointless to make this much smaller than the Class and ClassValueMap objects themselves.
424
* Must be a power of 2.
425
*/
426
private static final int INITIAL_ENTRIES = 32;
427
428
/** Build a backing map for ClassValues, relative the given type.
429
* Also, create an empty cache array and install it on the class.
430
*/
431
ClassValueMap(Class<?> type) {
432
this.type = type;
433
sizeCache(INITIAL_ENTRIES);
434
}
435
436
Entry<?>[] getCache() { return cacheArray; }
437
438
/** Initiate a query. Store a promise (placeholder) if there is no value yet. */
439
synchronized
440
<T> Entry<T> startEntry(ClassValue<T> classValue) {
441
@SuppressWarnings("unchecked") // one map has entries for all value types <T>
442
Entry<T> e = (Entry<T>) get(classValue.identity);
443
Version<T> v = classValue.version();
444
if (e == null) {
445
e = v.promise();
446
// The presence of a promise means that a value is pending for v.
447
// Eventually, finishEntry will overwrite the promise.
448
put(classValue.identity, e);
449
// Note that the promise is never entered into the cache!
450
return e;
451
} else if (e.isPromise()) {
452
// Somebody else has asked the same question.
453
// Let the races begin!
454
if (e.version() != v) {
455
e = v.promise();
456
put(classValue.identity, e);
457
}
458
return e;
459
} else {
460
// there is already a completed entry here; report it
461
if (e.version() != v) {
462
// There is a stale but valid entry here; make it fresh again.
463
// Once an entry is in the hash table, we don't care what its version is.
464
e = e.refreshVersion(v);
465
put(classValue.identity, e);
466
}
467
// Add to the cache, to enable the fast path, next time.
468
checkCacheLoad();
469
addToCache(classValue, e);
470
return e;
471
}
472
}
473
474
/** Finish a query. Overwrite a matching placeholder. Drop stale incoming values. */
475
synchronized
476
<T> Entry<T> finishEntry(ClassValue<T> classValue, Entry<T> e) {
477
@SuppressWarnings("unchecked") // one map has entries for all value types <T>
478
Entry<T> e0 = (Entry<T>) get(classValue.identity);
479
if (e == e0) {
480
// We can get here during exception processing, unwinding from computeValue.
481
assert(e.isPromise());
482
remove(classValue.identity);
483
return null;
484
} else if (e0 != null && e0.isPromise() && e0.version() == e.version()) {
485
// If e0 matches the intended entry, there has not been a remove call
486
// between the previous startEntry and now. So now overwrite e0.
487
Version<T> v = classValue.version();
488
if (e.version() != v)
489
e = e.refreshVersion(v);
490
put(classValue.identity, e);
491
// Add to the cache, to enable the fast path, next time.
492
checkCacheLoad();
493
addToCache(classValue, e);
494
return e;
495
} else {
496
// Some sort of mismatch; caller must try again.
497
return null;
498
}
499
}
500
501
/** Remove an entry. */
502
synchronized
503
void removeEntry(ClassValue<?> classValue) {
504
Entry<?> e = remove(classValue.identity);
505
if (e == null) {
506
// Uninitialized, and no pending calls to computeValue. No change.
507
} else if (e.isPromise()) {
508
// State is uninitialized, with a pending call to finishEntry.
509
// Since remove is a no-op in such a state, keep the promise
510
// by putting it back into the map.
511
put(classValue.identity, e);
512
} else {
513
// In an initialized state. Bump forward, and de-initialize.
514
classValue.bumpVersion();
515
// Make all cache elements for this guy go stale.
516
removeStaleEntries(classValue);
517
}
518
}
519
520
/** Change the value for an entry. */
521
synchronized
522
<T> void changeEntry(ClassValue<T> classValue, T value) {
523
@SuppressWarnings("unchecked") // one map has entries for all value types <T>
524
Entry<T> e0 = (Entry<T>) get(classValue.identity);
525
Version<T> version = classValue.version();
526
if (e0 != null) {
527
if (e0.version() == version && e0.value() == value)
528
// no value change => no version change needed
529
return;
530
classValue.bumpVersion();
531
removeStaleEntries(classValue);
532
}
533
Entry<T> e = makeEntry(version, value);
534
put(classValue.identity, e);
535
// Add to the cache, to enable the fast path, next time.
536
checkCacheLoad();
537
addToCache(classValue, e);
538
}
539
540
/// --------
541
/// Cache management.
542
/// --------
543
544
// Statics do not need synchronization.
545
546
/** Load the cache entry at the given (hashed) location. */
547
static Entry<?> loadFromCache(Entry<?>[] cache, int i) {
548
// non-racing cache.length : constant
549
// racing cache[i & (mask)] : null <=> Entry
550
return cache[i & (cache.length-1)];
551
// invariant: returned value is null or well-constructed (ready to match)
552
}
553
554
/** Look in the cache, at the home location for the given ClassValue. */
555
static <T> Entry<T> probeHomeLocation(Entry<?>[] cache, ClassValue<T> classValue) {
556
return classValue.castEntry(loadFromCache(cache, classValue.hashCodeForCache));
557
}
558
559
/** Given that first probe was a collision, retry at nearby locations. */
560
static <T> Entry<T> probeBackupLocations(Entry<?>[] cache, ClassValue<T> classValue) {
561
if (PROBE_LIMIT <= 0) return null;
562
// Probe the cache carefully, in a range of slots.
563
int mask = (cache.length-1);
564
int home = (classValue.hashCodeForCache & mask);
565
Entry<?> e2 = cache[home]; // victim, if we find the real guy
566
if (e2 == null) {
567
return null; // if nobody is at home, no need to search nearby
568
}
569
// assume !classValue.match(e2), but do not assert, because of races
570
int pos2 = -1;
571
for (int i = home + 1; i < home + PROBE_LIMIT; i++) {
572
Entry<?> e = cache[i & mask];
573
if (e == null) {
574
break; // only search within non-null runs
575
}
576
if (classValue.match(e)) {
577
// relocate colliding entry e2 (from cache[home]) to first empty slot
578
cache[home] = e;
579
if (pos2 >= 0) {
580
cache[i & mask] = Entry.DEAD_ENTRY;
581
} else {
582
pos2 = i;
583
}
584
cache[pos2 & mask] = ((entryDislocation(cache, pos2, e2) < PROBE_LIMIT)
585
? e2 // put e2 here if it fits
586
: Entry.DEAD_ENTRY);
587
return classValue.castEntry(e);
588
}
589
// Remember first empty slot, if any:
590
if (!e.isLive() && pos2 < 0) pos2 = i;
591
}
592
return null;
593
}
594
595
/** How far out of place is e? */
596
private static int entryDislocation(Entry<?>[] cache, int pos, Entry<?> e) {
597
ClassValue<?> cv = e.classValueOrNull();
598
if (cv == null) return 0; // entry is not live!
599
int mask = (cache.length-1);
600
return (pos - cv.hashCodeForCache) & mask;
601
}
602
603
/// --------
604
/// Below this line all functions are private, and assume synchronized access.
605
/// --------
606
607
private void sizeCache(int length) {
608
assert((length & (length-1)) == 0); // must be power of 2
609
cacheLoad = 0;
610
cacheLoadLimit = (int) ((double) length * CACHE_LOAD_LIMIT / 100);
611
cacheArray = new Entry<?>[length];
612
}
613
614
/** Make sure the cache load stays below its limit, if possible. */
615
private void checkCacheLoad() {
616
if (cacheLoad >= cacheLoadLimit) {
617
reduceCacheLoad();
618
}
619
}
620
private void reduceCacheLoad() {
621
removeStaleEntries();
622
if (cacheLoad < cacheLoadLimit)
623
return; // win
624
Entry<?>[] oldCache = getCache();
625
if (oldCache.length > HASH_MASK)
626
return; // lose
627
sizeCache(oldCache.length * 2);
628
for (Entry<?> e : oldCache) {
629
if (e != null && e.isLive()) {
630
addToCache(e);
631
}
632
}
633
}
634
635
/** Remove stale entries in the given range.
636
* Should be executed under a Map lock.
637
*/
638
private void removeStaleEntries(Entry<?>[] cache, int begin, int count) {
639
if (PROBE_LIMIT <= 0) return;
640
int mask = (cache.length-1);
641
int removed = 0;
642
for (int i = begin; i < begin + count; i++) {
643
Entry<?> e = cache[i & mask];
644
if (e == null || e.isLive())
645
continue; // skip null and live entries
646
Entry<?> replacement = null;
647
if (PROBE_LIMIT > 1) {
648
// avoid breaking up a non-null run
649
replacement = findReplacement(cache, i);
650
}
651
cache[i & mask] = replacement;
652
if (replacement == null) removed += 1;
653
}
654
cacheLoad = Math.max(0, cacheLoad - removed);
655
}
656
657
/** Clearing a cache slot risks disconnecting following entries
658
* from the head of a non-null run, which would allow them
659
* to be found via reprobes. Find an entry after cache[begin]
660
* to plug into the hole, or return null if none is needed.
661
*/
662
private Entry<?> findReplacement(Entry<?>[] cache, int home1) {
663
Entry<?> replacement = null;
664
int haveReplacement = -1, replacementPos = 0;
665
int mask = (cache.length-1);
666
for (int i2 = home1 + 1; i2 < home1 + PROBE_LIMIT; i2++) {
667
Entry<?> e2 = cache[i2 & mask];
668
if (e2 == null) break; // End of non-null run.
669
if (!e2.isLive()) continue; // Doomed anyway.
670
int dis2 = entryDislocation(cache, i2, e2);
671
if (dis2 == 0) continue; // e2 already optimally placed
672
int home2 = i2 - dis2;
673
if (home2 <= home1) {
674
// e2 can replace entry at cache[home1]
675
if (home2 == home1) {
676
// Put e2 exactly where he belongs.
677
haveReplacement = 1;
678
replacementPos = i2;
679
replacement = e2;
680
} else if (haveReplacement <= 0) {
681
haveReplacement = 0;
682
replacementPos = i2;
683
replacement = e2;
684
}
685
// And keep going, so we can favor larger dislocations.
686
}
687
}
688
if (haveReplacement >= 0) {
689
if (cache[(replacementPos+1) & mask] != null) {
690
// Be conservative, to avoid breaking up a non-null run.
691
cache[replacementPos & mask] = (Entry<?>) Entry.DEAD_ENTRY;
692
} else {
693
cache[replacementPos & mask] = null;
694
cacheLoad -= 1;
695
}
696
}
697
return replacement;
698
}
699
700
/** Remove stale entries in the range near classValue. */
701
private void removeStaleEntries(ClassValue<?> classValue) {
702
removeStaleEntries(getCache(), classValue.hashCodeForCache, PROBE_LIMIT);
703
}
704
705
/** Remove all stale entries, everywhere. */
706
private void removeStaleEntries() {
707
Entry<?>[] cache = getCache();
708
removeStaleEntries(cache, 0, cache.length + PROBE_LIMIT - 1);
709
}
710
711
/** Add the given entry to the cache, in its home location, unless it is out of date. */
712
private <T> void addToCache(Entry<T> e) {
713
ClassValue<T> classValue = e.classValueOrNull();
714
if (classValue != null)
715
addToCache(classValue, e);
716
}
717
718
/** Add the given entry to the cache, in its home location. */
719
private <T> void addToCache(ClassValue<T> classValue, Entry<T> e) {
720
if (PROBE_LIMIT <= 0) return; // do not fill cache
721
// Add e to the cache.
722
Entry<?>[] cache = getCache();
723
int mask = (cache.length-1);
724
int home = classValue.hashCodeForCache & mask;
725
Entry<?> e2 = placeInCache(cache, home, e, false);
726
if (e2 == null) return; // done
727
if (PROBE_LIMIT > 1) {
728
// try to move e2 somewhere else in his probe range
729
int dis2 = entryDislocation(cache, home, e2);
730
int home2 = home - dis2;
731
for (int i2 = home2; i2 < home2 + PROBE_LIMIT; i2++) {
732
if (placeInCache(cache, i2 & mask, e2, true) == null) {
733
return;
734
}
735
}
736
}
737
// Note: At this point, e2 is just dropped from the cache.
738
}
739
740
/** Store the given entry. Update cacheLoad, and return any live victim.
741
* 'Gently' means return self rather than dislocating a live victim.
742
*/
743
private Entry<?> placeInCache(Entry<?>[] cache, int pos, Entry<?> e, boolean gently) {
744
Entry<?> e2 = overwrittenEntry(cache[pos]);
745
if (gently && e2 != null) {
746
// do not overwrite a live entry
747
return e;
748
} else {
749
cache[pos] = e;
750
return e2;
751
}
752
}
753
754
/** Note an entry that is about to be overwritten.
755
* If it is not live, quietly replace it by null.
756
* If it is an actual null, increment cacheLoad,
757
* because the caller is going to store something
758
* in its place.
759
*/
760
private <T> Entry<T> overwrittenEntry(Entry<T> e2) {
761
if (e2 == null) cacheLoad += 1;
762
else if (e2.isLive()) return e2;
763
return null;
764
}
765
766
/** Percent loading of cache before resize. */
767
private static final int CACHE_LOAD_LIMIT = 67; // 0..100
768
/** Maximum number of probes to attempt. */
769
private static final int PROBE_LIMIT = 6; // 1..
770
// N.B. Set PROBE_LIMIT=0 to disable all fast paths.
771
}
772
}
773
774