-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathClassValueMap.java
397 lines (359 loc) · 13.5 KB
/
ClassValueMap.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
package com.cedarsoftware.util;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
/**
* A Map implementation keyed on Class objects that leverages a ClassValue cache for extremely
* fast lookups. This specialized collection is designed for scenarios where you frequently
* need to retrieve values associated with Class keys.
*
* <h2>Performance Advantages</h2>
* <p>
* ClassValueMap provides significantly faster {@code get()} operations compared to standard
* Map implementations:
* <ul>
* <li>2-10x faster than HashMap for key lookups</li>
* <li>3-15x faster than ConcurrentHashMap for concurrent access patterns</li>
* <li>The performance advantage increases with contention (multiple threads)</li>
* <li>Most significant when looking up the same class keys repeatedly</li>
* </ul>
*
* <h2>How It Works</h2>
* <p>
* The implementation utilizes Java's {@link ClassValue} mechanism, which is specially optimized
* in the JVM through:
* <ul>
* <li>Thread-local caching for reduced contention</li>
* <li>Identity-based lookups (faster than equality checks)</li>
* <li>Special VM support that connects directly to Class metadata structures</li>
* <li>Optimized memory layout that can reduce cache misses</li>
* </ul>
*
* <h2>Drop-in Replacement</h2>
* <p>
* ClassValueMap is designed as a drop-in replacement for existing maps with Class keys:
* <ul>
* <li>Fully implements the {@link java.util.Map} and {@link java.util.concurrent.ConcurrentMap} interfaces</li>
* <li>Supports all standard map operations (put, remove, clear, etc.)</li>
* <li>Handles null keys and null values just like standard map implementations</li>
* <li>Thread-safe for all operations</li>
* </ul>
*
* <h2>Ideal Use Cases</h2>
* <p>
* ClassValueMap is ideal for:
* <ul>
* <li>High read-to-write ratio scenarios (read-mostly workloads)</li>
* <li>Caches for class-specific handlers, factories, or metadata</li>
* <li>Performance-critical operations in hot code paths</li>
* <li>Type registries in frameworks (serializers, converters, validators)</li>
* <li>Class capability or feature mappings</li>
* <li>Any system that frequently maps from Class objects to associated data</li>
* </ul>
*
* <h2>Trade-offs</h2>
* <p>
* The performance benefits come with some trade-offs:
* <ul>
* <li>Higher memory usage (maintains both a backing map and ClassValue cache)</li>
* <li>Write operations (put/remove) aren't faster and may be slightly slower</li>
* <li>Only Class keys benefit from the optimized lookups</li>
* </ul>
*
* <h2>Thread Safety</h2>
* <p>
* This implementation is thread-safe for all operations and implements ConcurrentMap.
*
* <h2>Usage Example</h2>
* <pre>{@code
* // Create a registry of class handlers
* ClassValueMap<Handler> handlerRegistry = new ClassValueMap<>();
* handlerRegistry.put(String.class, new StringHandler());
* handlerRegistry.put(Integer.class, new IntegerHandler());
* handlerRegistry.put(List.class, new ListHandler());
*
* // Fast lookup in a performance-critical context
* public void process(Object obj) {
* Handler handler = handlerRegistry.get(obj.getClass());
* if (handler != null) {
* handler.handle(obj);
* } else {
* // Default handling
* }
* }
* }</pre>
*
* <h2>Important Performance Warning</h2>
* <p>
* Wrapping this class with standard collection wrappers like {@code Collections.unmodifiableMap()}
* or {@code Collections.newSetFromMap()} will destroy the {@code ClassValue} performance benefits.
* Always use the raw {@code ClassValueMap} directly or use the provided {@code unmodifiableView()} method
* if immutability is required.
* </p>
* @see ClassValue
* @see Map
* @see ConcurrentMap
*
* @param <V> the type of mapped values
*
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* 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
* <br><br>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">License</a>
* <br><br>
* 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.
*/
public class ClassValueMap<V> extends AbstractMap<Class<?>, V> implements ConcurrentMap<Class<?>, V> {
// Sentinel used by the ClassValue cache to indicate "no value"
private static final Object NO_VALUE = new Object();
// Backing map that supports null keys and null values.
private final ConcurrentMap<Class<?>, V> backingMap = new ConcurrentHashMapNullSafe<>();
// Storage for the null key (since ClassValue cannot handle null keys)
private final AtomicReference<V> nullKeyValue = new AtomicReference<>();
// A ClassValue cache for extremely fast lookups on non-null Class keys.
// When a key is missing from backingMap, we return NO_VALUE.
private final ClassValue<Object> cache = new ClassValue<Object>() {
@Override
protected Object computeValue(Class<?> key) {
V value = backingMap.get(key);
return (value != null || backingMap.containsKey(key)) ? value : NO_VALUE;
}
};
/**
* Creates a ClassValueMap
*/
public ClassValueMap() {
}
/**
* Creates a ClassValueMap containing the mappings from the specified map.
*
* @param map the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public ClassValueMap(Map<? extends Class<?>, ? extends V> map) {
if (map == null) {
throw new NullPointerException("Map cannot be null");
}
putAll(map);
}
@Override
public V get(Object key) {
if (key == null) {
return nullKeyValue.get();
}
if (!(key instanceof Class)) {
return null;
}
Class<?> clazz = (Class<?>) key;
Object value = cache.get(clazz);
return (value == NO_VALUE) ? null : (V) value;
}
@Override
public V put(Class<?> key, V value) {
if (key == null) {
return nullKeyValue.getAndSet(value);
}
V old = backingMap.put(key, value);
cache.remove(key); // Invalidate cached value for this key.
return old;
}
@Override
public V remove(Object key) {
if (key == null) {
return nullKeyValue.getAndSet(null);
}
if (!(key instanceof Class)) {
return null;
}
Class<?> clazz = (Class<?>) key;
V old = backingMap.remove(clazz);
cache.remove(clazz);
return old;
}
@Override
public boolean containsKey(Object key) {
if (key == null) {
return nullKeyValue.get() != null;
}
if (!(key instanceof Class)) {
return false;
}
Class<?> clazz = (Class<?>) key;
return cache.get(clazz) != NO_VALUE;
}
@Override
public void clear() {
// Save the keys before clearing the map
Set<Class<?>> keysToInvalidate = new HashSet<>(backingMap.keySet());
// Now clear the map and null key value
backingMap.clear();
nullKeyValue.set(null);
// Invalidate cache entries for all the saved keys
for (Class<?> key : keysToInvalidate) {
cache.remove(key);
}
}
@Override
public int size() {
// Size is the backingMap size plus 1 if a null-key mapping exists.
return backingMap.size() + (nullKeyValue.get() != null ? 1 : 0);
}
@Override
public Set<Entry<Class<?>, V>> entrySet() {
// Combine the null-key entry (if present) with the backingMap entries.
return new AbstractSet<Entry<Class<?>, V>>() {
@Override
public Iterator<Entry<Class<?>, V>> iterator() {
// First, create an iterator over the backing map entries.
Iterator<Entry<Class<?>, V>> backingIterator = backingMap.entrySet().iterator();
// And prepare the null-key entry if one exists.
final Entry<Class<?>, V> nullEntry =
(nullKeyValue.get() != null) ? new SimpleImmutableEntry<>(null, nullKeyValue.get()) : null;
return new Iterator<Entry<Class<?>, V>>() {
private boolean nullEntryReturned = (nullEntry == null);
@Override
public boolean hasNext() {
return !nullEntryReturned || backingIterator.hasNext();
}
@Override
public Entry<Class<?>, V> next() {
if (!nullEntryReturned) {
nullEntryReturned = true;
return nullEntry;
}
return backingIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Removal not supported via iterator.");
}
};
}
@Override
public int size() {
return ClassValueMap.this.size();
}
};
}
// The remaining ConcurrentMap methods (putIfAbsent, replace, etc.) can be implemented by
// delegating to the backingMap and invalidating the cache as needed.
@Override
public V putIfAbsent(Class<?> key, V value) {
if (key == null) {
return nullKeyValue.compareAndSet(null, value) ? null : nullKeyValue.get();
}
V prev = backingMap.putIfAbsent(key, value);
cache.remove(key);
return prev;
}
@Override
public boolean remove(Object key, Object value) {
if (key == null) {
return nullKeyValue.compareAndSet((V) value, null);
}
if (!(key instanceof Class)) {
return false;
}
boolean removed = backingMap.remove(key, value);
cache.remove((Class<?>) key);
return removed;
}
@Override
public boolean replace(Class<?> key, V oldValue, V newValue) {
if (key == null) {
return nullKeyValue.compareAndSet(oldValue, newValue);
}
boolean replaced = backingMap.replace(key, oldValue, newValue);
cache.remove(key);
return replaced;
}
@Override
public V replace(Class<?> key, V value) {
if (key == null) {
V prev = nullKeyValue.get();
nullKeyValue.set(value);
return prev;
}
V replaced = backingMap.replace(key, value);
cache.remove(key);
return replaced;
}
@Override
public Collection<V> values() {
// Combine values from the backingMap with the null-key value (if present)
Set<V> vals = new HashSet<>(backingMap.values());
if (nullKeyValue.get() != null) {
vals.add(nullKeyValue.get());
}
return vals;
}
/**
* Returns an unmodifiable view of this map that preserves ClassValue performance benefits.
* Unlike Collections.unmodifiableMap(), this method returns a view that maintains
* the fast lookup performance for Class keys.
*
* @return an unmodifiable view of this map with preserved performance characteristics
*/
public Map<Class<?>, V> unmodifiableView() {
final ClassValueMap<V> thisMap = this;
return new AbstractMap<Class<?>, V>() {
@Override
public Set<Entry<Class<?>, V>> entrySet() {
return Collections.unmodifiableSet(thisMap.entrySet());
}
@Override
public V get(Object key) {
return thisMap.get(key); // Preserves ClassValue optimization
}
@Override
public boolean containsKey(Object key) {
return thisMap.containsKey(key); // Preserves ClassValue optimization
}
@Override
public Set<Class<?>> keySet() {
return Collections.unmodifiableSet(thisMap.keySet());
}
@Override
public Collection<V> values() {
return Collections.unmodifiableCollection(thisMap.values());
}
@Override
public int size() {
return thisMap.size();
}
// All mutator methods throw UnsupportedOperationException
@Override
public V put(Class<?> key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends Class<?>, ? extends V> m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
};
}
}