|
8 | 8 |
|
9 | 9 | package org.elasticsearch.common.util;
|
10 | 10 |
|
11 |
| -import org.elasticsearch.Assertions; |
12 |
| - |
13 | 11 | import java.util.Collections;
|
| 12 | +import java.util.HashMap; |
14 | 13 | import java.util.Map;
|
15 | 14 | import java.util.Objects;
|
| 15 | +import java.util.Set; |
16 | 16 | import java.util.stream.Collectors;
|
17 | 17 |
|
18 | 18 | public class Maps {
|
@@ -49,22 +49,31 @@ public static <K, V> boolean deepEquals(Map<K, V> left, Map<K, V> right) {
|
49 | 49 | public static <K, V> Map<K, V> copyMapWithRemovedEntry(final Map<K, V> map, final K key) {
|
50 | 50 | Objects.requireNonNull(map);
|
51 | 51 | Objects.requireNonNull(key);
|
52 |
| - assertImmutableMap(map, key, map.get(key)); |
| 52 | + assert checkIsImmutableMap(map, key, map.get(key)); |
53 | 53 | return map.entrySet().stream().filter(k -> key.equals(k.getKey()) == false)
|
54 | 54 | .collect(Collectors.collectingAndThen(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
|
55 | 55 | Collections::<K, V>unmodifiableMap));
|
56 | 56 | }
|
57 | 57 |
|
58 |
| - private static <K, V> void assertImmutableMap(final Map<K, V> map, final K key, final V value) { |
59 |
| - if (Assertions.ENABLED) { |
60 |
| - boolean immutable; |
61 |
| - try { |
62 |
| - map.put(key, value); |
63 |
| - immutable = false; |
64 |
| - } catch (final UnsupportedOperationException e) { |
65 |
| - immutable = true; |
66 |
| - } |
67 |
| - assert immutable : "expected an immutable map but was [" + map.getClass() + "]"; |
| 58 | + // map classes that are known to be immutable, used to speed up immutability check in #assertImmutableMap |
| 59 | + private static final Set<Class<?>> IMMUTABLE_MAP_CLASSES = org.elasticsearch.core.Set.of( |
| 60 | + Collections.emptyMap().getClass(), |
| 61 | + Collections.unmodifiableMap(new HashMap<>()).getClass(), |
| 62 | + org.elasticsearch.core.Map.of().getClass(), |
| 63 | + org.elasticsearch.core.Map.of("a", "b").getClass() |
| 64 | + ); |
| 65 | + |
| 66 | + private static <K, V> boolean checkIsImmutableMap(final Map<K, V> map, final K key, final V value) { |
| 67 | + // check in the known immutable classes map first, most of the time we don't need to actually do the put and throw which is slow to |
| 68 | + // the point of visibly slowing down internal cluster tests without this short-cut |
| 69 | + if (IMMUTABLE_MAP_CLASSES.contains(map.getClass())) { |
| 70 | + return true; |
| 71 | + } |
| 72 | + try { |
| 73 | + map.put(key, value); |
| 74 | + return false; |
| 75 | + } catch (final UnsupportedOperationException ignored) { |
68 | 76 | }
|
| 77 | + return true; |
69 | 78 | }
|
70 | 79 | }
|
0 commit comments