Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.desktop/share/classes/com/sun/beans/util/Cache.java
41171 views
1
/*
2
* Copyright (c) 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
package com.sun.beans.util;
26
27
import java.lang.ref.ReferenceQueue;
28
import java.lang.ref.SoftReference;
29
import java.lang.ref.WeakReference;
30
import java.util.Objects;
31
32
/**
33
* Hash table based implementation of the cache,
34
* which allows to use weak or soft references for keys and values.
35
* An entry in a {@code Cache} will automatically be removed
36
* when its key or value is no longer in ordinary use.
37
*
38
* @author Sergey Malenkov
39
* @since 1.8
40
*/
41
public abstract class Cache<K,V> {
42
private static final int MAXIMUM_CAPACITY = 1 << 30; // maximum capacity MUST be a power of two <= 1<<30
43
44
private final boolean identity; // defines whether the identity comparison is used
45
private final Kind keyKind; // a reference kind for the cache keys
46
private final Kind valueKind; // a reference kind for the cache values
47
48
private final ReferenceQueue<Object> queue = new ReferenceQueue<>(); // queue for references to remove
49
50
private volatile CacheEntry<K,V>[] table = newTable(1 << 3); // table's length MUST be a power of two
51
private int threshold = 6; // the next size value at which to resize
52
private int size; // the number of key-value mappings contained in this map
53
54
/**
55
* Creates a corresponding value for the specified key.
56
*
57
* @param key a key that can be used to create a value
58
* @return a corresponding value for the specified key
59
*/
60
public abstract V create(K key);
61
62
/**
63
* Constructs an empty {@code Cache}.
64
* The default initial capacity is 8.
65
* The default load factor is 0.75.
66
*
67
* @param keyKind a reference kind for keys
68
* @param valueKind a reference kind for values
69
*
70
* @throws NullPointerException if {@code keyKind} or {@code valueKind} are {@code null}
71
*/
72
public Cache(Kind keyKind, Kind valueKind) {
73
this(keyKind, valueKind, false);
74
}
75
76
/**
77
* Constructs an empty {@code Cache}
78
* with the specified comparison method.
79
* The default initial capacity is 8.
80
* The default load factor is 0.75.
81
*
82
* @param keyKind a reference kind for keys
83
* @param valueKind a reference kind for values
84
* @param identity defines whether reference-equality
85
* is used in place of object-equality
86
*
87
* @throws NullPointerException if {@code keyKind} or {@code valueKind} are {@code null}
88
*/
89
public Cache(Kind keyKind, Kind valueKind, boolean identity) {
90
Objects.requireNonNull(keyKind, "keyKind");
91
Objects.requireNonNull(valueKind, "valueKind");
92
this.keyKind = keyKind;
93
this.valueKind = valueKind;
94
this.identity = identity;
95
}
96
97
/**
98
* Returns the value to which the specified key is mapped,
99
* or {@code null} if there is no mapping for the key.
100
*
101
* @param key the key whose cached value is to be returned
102
* @return a value to which the specified key is mapped,
103
* or {@code null} if there is no mapping for {@code key}
104
*
105
* @throws NullPointerException if {@code key} is {@code null}
106
* or corresponding value is {@code null}
107
*/
108
public final V get(K key) {
109
Objects.requireNonNull(key, "key");
110
removeStaleEntries();
111
int hash = hash(key);
112
// unsynchronized search improves performance
113
// the null value does not mean that there are no needed entry
114
CacheEntry<K,V>[] table = this.table; // unsynchronized access
115
V current = getEntryValue(key, hash, table[index(hash, table)]);
116
if (current != null) {
117
return current;
118
}
119
synchronized (this.queue) {
120
// synchronized search improves stability
121
// we must create and add new value if there are no needed entry
122
current = getEntryValue(key, hash, this.table[index(hash, this.table)]);
123
if (current != null) {
124
return current;
125
}
126
V value = create(key);
127
Objects.requireNonNull(value, "value");
128
int index = index(hash, this.table);
129
this.table[index] = new CacheEntry<>(hash, key, value, this.table[index]);
130
if (++this.size >= this.threshold) {
131
if (this.table.length == MAXIMUM_CAPACITY) {
132
this.threshold = Integer.MAX_VALUE;
133
} else {
134
removeStaleEntries();
135
table = newTable(this.table.length << 1);
136
transfer(this.table, table);
137
// If ignoring null elements and processing ref queue caused massive
138
// shrinkage, then restore old table. This should be rare, but avoids
139
// unbounded expansion of garbage-filled tables.
140
if (this.size >= this.threshold / 2) {
141
this.table = table;
142
this.threshold <<= 1;
143
} else {
144
transfer(table, this.table);
145
}
146
removeStaleEntries();
147
}
148
}
149
return value;
150
}
151
}
152
153
/**
154
* Removes the cached value that corresponds to the specified key.
155
*
156
* @param key the key whose mapping is to be removed from this cache
157
*/
158
public final void remove(K key) {
159
if (key != null) {
160
synchronized (this.queue) {
161
removeStaleEntries();
162
int hash = hash(key);
163
int index = index(hash, this.table);
164
CacheEntry<K,V> prev = this.table[index];
165
CacheEntry<K,V> entry = prev;
166
while (entry != null) {
167
CacheEntry<K,V> next = entry.next;
168
if (entry.matches(hash, key)) {
169
if (entry == prev) {
170
this.table[index] = next;
171
} else {
172
prev.next = next;
173
}
174
entry.unlink();
175
break;
176
}
177
prev = entry;
178
entry = next;
179
}
180
}
181
}
182
}
183
184
/**
185
* Removes all of the mappings from this cache.
186
* It will be empty after this call returns.
187
*/
188
public final void clear() {
189
synchronized (this.queue) {
190
int index = this.table.length;
191
while (0 < index--) {
192
CacheEntry<K,V> entry = this.table[index];
193
while (entry != null) {
194
CacheEntry<K,V> next = entry.next;
195
entry.unlink();
196
entry = next;
197
}
198
this.table[index] = null;
199
}
200
while (null != this.queue.poll()) {
201
// Clear out the reference queue.
202
}
203
}
204
}
205
206
/**
207
* Retrieves object hash code and applies a supplemental hash function
208
* to the result hash, which defends against poor quality hash functions.
209
* This is critical because {@code Cache} uses power-of-two length hash tables,
210
* that otherwise encounter collisions for hashCodes that do not differ
211
* in lower bits.
212
*
213
* @param key the object which hash code is to be calculated
214
* @return a hash code value for the specified object
215
*/
216
private int hash(Object key) {
217
if (this.identity) {
218
int hash = System.identityHashCode(key);
219
return (hash << 1) - (hash << 8);
220
}
221
int hash = key.hashCode();
222
// This function ensures that hashCodes that differ only by
223
// constant multiples at each bit position have a bounded
224
// number of collisions (approximately 8 at default load factor).
225
hash ^= (hash >>> 20) ^ (hash >>> 12);
226
return hash ^ (hash >>> 7) ^ (hash >>> 4);
227
}
228
229
/**
230
* Returns index of the specified hash code in the given table.
231
* Note that the table size must be a power of two.
232
*
233
* @param hash the hash code
234
* @param table the table
235
* @return an index of the specified hash code in the given table
236
*/
237
private static int index(int hash, Object[] table) {
238
return hash & (table.length - 1);
239
}
240
241
/**
242
* Creates a new array for the cache entries.
243
*
244
* @param size requested capacity MUST be a power of two
245
* @return a new array for the cache entries
246
*/
247
@SuppressWarnings({"unchecked", "rawtypes"})
248
private CacheEntry<K,V>[] newTable(int size) {
249
return (CacheEntry<K,V>[]) new CacheEntry[size];
250
}
251
252
private V getEntryValue(K key, int hash, CacheEntry<K,V> entry) {
253
while (entry != null) {
254
if (entry.matches(hash, key)) {
255
return entry.value.getReferent();
256
}
257
entry = entry.next;
258
}
259
return null;
260
}
261
262
private void removeStaleEntries() {
263
Object reference = this.queue.poll();
264
if (reference != null) {
265
synchronized (this.queue) {
266
do {
267
if (reference instanceof Ref) {
268
@SuppressWarnings("rawtypes")
269
Ref ref = (Ref) reference;
270
@SuppressWarnings("unchecked")
271
CacheEntry<K,V> owner = (CacheEntry<K,V>) ref.getOwner();
272
if (owner != null) {
273
int index = index(owner.hash, this.table);
274
CacheEntry<K,V> prev = this.table[index];
275
CacheEntry<K,V> entry = prev;
276
while (entry != null) {
277
CacheEntry<K,V> next = entry.next;
278
if (entry == owner) {
279
if (entry == prev) {
280
this.table[index] = next;
281
} else {
282
prev.next = next;
283
}
284
entry.unlink();
285
break;
286
}
287
prev = entry;
288
entry = next;
289
}
290
}
291
}
292
reference = this.queue.poll();
293
}
294
while (reference != null);
295
}
296
}
297
}
298
299
private void transfer(CacheEntry<K,V>[] oldTable, CacheEntry<K,V>[] newTable) {
300
int oldIndex = oldTable.length;
301
while (0 < oldIndex--) {
302
CacheEntry<K,V> entry = oldTable[oldIndex];
303
oldTable[oldIndex] = null;
304
while (entry != null) {
305
CacheEntry<K,V> next = entry.next;
306
if (entry.key.isStale() || entry.value.isStale()) {
307
entry.unlink();
308
} else {
309
int newIndex = index(entry.hash, newTable);
310
entry.next = newTable[newIndex];
311
newTable[newIndex] = entry;
312
}
313
entry = next;
314
}
315
}
316
}
317
318
/**
319
* Represents a cache entry (key-value pair).
320
*/
321
private final class CacheEntry<K,V> {
322
private final int hash;
323
private final Ref<K> key;
324
private final Ref<V> value;
325
private volatile CacheEntry<K,V> next;
326
327
/**
328
* Constructs an entry for the cache.
329
*
330
* @param hash the hash code calculated for the entry key
331
* @param key the entry key
332
* @param value the initial value of the entry
333
* @param next the next entry in a chain
334
*/
335
private CacheEntry(int hash, K key, V value, CacheEntry<K,V> next) {
336
this.hash = hash;
337
this.key = Cache.this.keyKind.create(this, key, Cache.this.queue);
338
this.value = Cache.this.valueKind.create(this, value, Cache.this.queue);
339
this.next = next;
340
}
341
342
/**
343
* Determines whether the entry has the given key with the given hash code.
344
*
345
* @param hash an expected hash code
346
* @param object an object to be compared with the entry key
347
* @return {@code true} if the entry has the given key with the given hash code;
348
* {@code false} otherwise
349
*/
350
private boolean matches(int hash, Object object) {
351
if (this.hash != hash) {
352
return false;
353
}
354
Object key = this.key.getReferent();
355
return (key == object) || !Cache.this.identity && (key != null) && key.equals(object);
356
}
357
358
/**
359
* Marks the entry as actually removed from the cache.
360
*/
361
private void unlink() {
362
this.next = null;
363
this.key.removeOwner();
364
this.value.removeOwner();
365
Cache.this.size--;
366
}
367
}
368
369
/**
370
* Basic interface for references.
371
* It defines the operations common for the all kind of references.
372
*
373
* @param <T> the type of object to refer
374
*/
375
private static interface Ref<T> {
376
/**
377
* Returns the object that possesses information about the reference.
378
*
379
* @return the owner of the reference or {@code null} if the owner is unknown
380
*/
381
Object getOwner();
382
383
/**
384
* Returns the object to refer.
385
*
386
* @return the referred object or {@code null} if it was collected
387
*/
388
T getReferent();
389
390
/**
391
* Determines whether the referred object was taken by the garbage collector or not.
392
*
393
* @return {@code true} if the referred object was collected
394
*/
395
boolean isStale();
396
397
/**
398
* Marks this reference as removed from the cache.
399
*/
400
void removeOwner();
401
}
402
403
/**
404
* Represents a reference kind.
405
*/
406
public static enum Kind {
407
STRONG {
408
<T> Ref<T> create(Object owner, T value, ReferenceQueue<? super T> queue) {
409
return new Strong<>(owner, value);
410
}
411
},
412
SOFT {
413
<T> Ref<T> create(Object owner, T referent, ReferenceQueue<? super T> queue) {
414
return (referent == null)
415
? new Strong<>(owner, referent)
416
: new Soft<>(owner, referent, queue);
417
}
418
},
419
WEAK {
420
<T> Ref<T> create(Object owner, T referent, ReferenceQueue<? super T> queue) {
421
return (referent == null)
422
? new Strong<>(owner, referent)
423
: new Weak<>(owner, referent, queue);
424
}
425
};
426
427
/**
428
* Creates a reference to the specified object.
429
*
430
* @param <T> the type of object to refer
431
* @param owner the owner of the reference, if needed
432
* @param referent the object to refer
433
* @param queue the queue to register the reference with,
434
* or {@code null} if registration is not required
435
* @return the reference to the specified object
436
*/
437
abstract <T> Ref<T> create(Object owner, T referent, ReferenceQueue<? super T> queue);
438
439
/**
440
* This is an implementation of the {@link Cache.Ref} interface
441
* that uses the strong references that prevent their referents
442
* from being made finalizable, finalized, and then reclaimed.
443
*
444
* @param <T> the type of object to refer
445
*/
446
private static final class Strong<T> implements Ref<T> {
447
private Object owner;
448
private final T referent;
449
450
/**
451
* Creates a strong reference to the specified object.
452
*
453
* @param owner the owner of the reference, if needed
454
* @param referent the non-null object to refer
455
*/
456
private Strong(Object owner, T referent) {
457
this.owner = owner;
458
this.referent = referent;
459
}
460
461
/**
462
* Returns the object that possesses information about the reference.
463
*
464
* @return the owner of the reference or {@code null} if the owner is unknown
465
*/
466
public Object getOwner() {
467
return this.owner;
468
}
469
470
/**
471
* Returns the object to refer.
472
*
473
* @return the referred object
474
*/
475
public T getReferent() {
476
return this.referent;
477
}
478
479
/**
480
* Determines whether the referred object was taken by the garbage collector or not.
481
*
482
* @return {@code true} if the referred object was collected
483
*/
484
public boolean isStale() {
485
return false;
486
}
487
488
/**
489
* Marks this reference as removed from the cache.
490
*/
491
public void removeOwner() {
492
this.owner = null;
493
}
494
}
495
496
/**
497
* This is an implementation of the {@link Cache.Ref} interface
498
* that uses the soft references that are cleared at the discretion
499
* of the garbage collector in response to a memory request.
500
*
501
* @param <T> the type of object to refer
502
* @see java.lang.ref.SoftReference
503
*/
504
private static final class Soft<T> extends SoftReference<T> implements Ref<T> {
505
private Object owner;
506
507
/**
508
* Creates a soft reference to the specified object.
509
*
510
* @param owner the owner of the reference, if needed
511
* @param referent the non-null object to refer
512
* @param queue the queue to register the reference with,
513
* or {@code null} if registration is not required
514
*/
515
private Soft(Object owner, T referent, ReferenceQueue<? super T> queue) {
516
super(referent, queue);
517
this.owner = owner;
518
}
519
520
/**
521
* Returns the object that possesses information about the reference.
522
*
523
* @return the owner of the reference or {@code null} if the owner is unknown
524
*/
525
public Object getOwner() {
526
return this.owner;
527
}
528
529
/**
530
* Returns the object to refer.
531
*
532
* @return the referred object or {@code null} if it was collected
533
*/
534
public T getReferent() {
535
return get();
536
}
537
538
/**
539
* Determines whether the referred object was taken by the garbage collector or not.
540
*
541
* @return {@code true} if the referred object was collected
542
*/
543
public boolean isStale() {
544
return null == get();
545
}
546
547
/**
548
* Marks this reference as removed from the cache.
549
*/
550
public void removeOwner() {
551
this.owner = null;
552
}
553
}
554
555
/**
556
* This is an implementation of the {@link Cache.Ref} interface
557
* that uses the weak references that do not prevent their referents
558
* from being made finalizable, finalized, and then reclaimed.
559
*
560
* @param <T> the type of object to refer
561
* @see java.lang.ref.WeakReference
562
*/
563
private static final class Weak<T> extends WeakReference<T> implements Ref<T> {
564
private Object owner;
565
566
/**
567
* Creates a weak reference to the specified object.
568
*
569
* @param owner the owner of the reference, if needed
570
* @param referent the non-null object to refer
571
* @param queue the queue to register the reference with,
572
* or {@code null} if registration is not required
573
*/
574
private Weak(Object owner, T referent, ReferenceQueue<? super T> queue) {
575
super(referent, queue);
576
this.owner = owner;
577
}
578
579
/**
580
* Returns the object that possesses information about the reference.
581
*
582
* @return the owner of the reference or {@code null} if the owner is unknown
583
*/
584
public Object getOwner() {
585
return this.owner;
586
}
587
588
/**
589
* Returns the object to refer.
590
*
591
* @return the referred object or {@code null} if it was collected
592
*/
593
public T getReferent() {
594
return get();
595
}
596
597
/**
598
* Determines whether the referred object was taken by the garbage collector or not.
599
*
600
* @return {@code true} if the referred object was collected
601
*/
602
public boolean isStale() {
603
return null == get();
604
}
605
606
/**
607
* Marks this reference as removed from the cache.
608
*/
609
public void removeOwner() {
610
this.owner = null;
611
}
612
}
613
}
614
}
615
616