dc979695e94d9e117d66298f976959e0ddeb79a0
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / LazyBindingMap.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableMap.Builder;
15 import java.lang.invoke.MethodHandles;
16 import java.lang.invoke.VarHandle;
17 import java.util.AbstractMap;
18 import java.util.Collection;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.Set;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.mdsal.binding.dom.codec.impl.MapCodecContext.Unordered;
24 import org.opendaylight.yangtools.concepts.Immutable;
25 import org.opendaylight.yangtools.yang.binding.DataObject;
26 import org.opendaylight.yangtools.yang.binding.Key;
27 import org.opendaylight.yangtools.yang.binding.KeyAware;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
29 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Lazily-populated Map of binding DTOs. This implementation acts as the main entry point, so that we can decide on the
36  * translation strategy we are going to use. We make that decision based on the first method that touches the mappings
37  * (or materializes a view).
38  *
39  * @param <K> key type
40  * @param <V> value type
41  */
42 final class LazyBindingMap<K extends Key<V>, V extends DataObject & KeyAware<K>>
43         extends AbstractMap<K, V> implements Immutable {
44     private static final Logger LOG = LoggerFactory.getLogger(LazyBindingMap.class);
45     private static final String LAZY_CUTOFF_PROPERTY =
46             "org.opendaylight.mdsal.binding.dom.codec.impl.LazyBindingMap.max-eager-elements";
47     private static final int DEFAULT_LAZY_CUTOFF = 1;
48     @VisibleForTesting
49     static final int LAZY_CUTOFF;
50
51     private static final VarHandle STATE;
52
53     static {
54         try {
55             STATE = MethodHandles.lookup().findVarHandle(LazyBindingMap.class, "state",
56                 State.class);
57         } catch (NoSuchFieldException | IllegalAccessException e) {
58             throw new ExceptionInInitializerError(e);
59         }
60
61         final int value = Integer.getInteger(LAZY_CUTOFF_PROPERTY, DEFAULT_LAZY_CUTOFF);
62         if (value < 0) {
63             LOG.info("Lazy population of maps disabled");
64             LAZY_CUTOFF = Integer.MAX_VALUE;
65         } else {
66             LOG.info("Using lazy population for maps larger than {} element(s)", value);
67             LAZY_CUTOFF = value;
68         }
69     }
70
71     private final @NonNull Unordered<K, V> codec;
72     private final @NonNull MapNode mapNode;
73
74     // Used via VarHandle above
75     @SuppressWarnings("unused")
76     private volatile State<K, V> state;
77
78     private LazyBindingMap(final Unordered<K, V> codec, final MapNode mapNode) {
79         this.codec = requireNonNull(codec);
80         this.mapNode = requireNonNull(mapNode);
81     }
82
83     static <K extends Key<V>, V extends DataObject & KeyAware<K>> @NonNull Map<K, V> of(final Unordered<K, V> codec,
84             final MapNode mapNode, final int size) {
85         if (size == 1) {
86             // Do not bother with lazy instantiation in case of a singleton
87             final V entry = codec.createBindingProxy(mapNode.body().iterator().next());
88             return Map.of(entry.key(), entry);
89         }
90         return size > LAZY_CUTOFF ? new LazyBindingMap<>(codec, mapNode) : eagerMap(codec, mapNode, size);
91     }
92
93     private static <K extends Key<V>, V extends DataObject & KeyAware<K>> @NonNull Map<K, V> eagerMap(
94             final Unordered<K, V> codec, final MapNode mapNode, final int size) {
95         final Builder<K, V> builder = ImmutableMap.builderWithExpectedSize(size);
96         for (MapEntryNode node : mapNode.body()) {
97             final V entry = codec.createBindingProxy(node);
98             builder.put(entry.key(), entry);
99         }
100         return builder.build();
101     }
102
103     @Override
104     public int size() {
105         return mapNode.size();
106     }
107
108     @Override
109     public V remove(final Object key) {
110         throw uoe();
111     }
112
113     @Override
114     @SuppressWarnings("checkstyle:parameterName")
115     public void putAll(final Map<? extends K, ? extends V> m) {
116         throw uoe();
117     }
118
119     @Override
120     public void clear() {
121         throw uoe();
122     }
123
124     @Override
125     public boolean containsKey(final Object key) {
126         return lookupState().containsKey(requireNonNull(key));
127     }
128
129     @Override
130     public boolean containsValue(final Object value) {
131         /*
132          * This implementation relies on the relationship specified by KeyAware/Key and its use in binding objects. The
133          * key is a wrapper object composed of a subset (or all) properties in the value, i.e. we have a partial index.
134          *
135          * Instead of performing an O(N) search, we extract the key from the value, look the for the corresponding
136          * mapping. If we find a mapping we check if the mapped value equals the the value being looked up.
137          *
138          * Note we prefer throwing ClassCastException/NullPointerException when presented with null or an object which
139          * cannot possibly be contained in this map.
140          */
141         final V cast = codec.getBindingClass().cast(requireNonNull(value));
142         final V found = get(cast.key());
143         return found != null && cast.equals(found);
144     }
145
146     @Override
147     public V get(final Object key) {
148         return lookupState().get(requireNonNull(key));
149     }
150
151     @Override
152     public Set<K> keySet() {
153         return iterState().keySet();
154     }
155
156     @Override
157     public Collection<V> values() {
158         return iterState().values();
159     }
160
161     @Override
162     public Set<Entry<K, V>> entrySet() {
163         return iterState().entrySet();
164     }
165
166     @NonNull V createValue(final MapEntryNode node) {
167         return codec.createBindingProxy(node);
168     }
169
170     Optional<V> lookupValue(final @NonNull Object key) {
171         final NodeIdentifierWithPredicates childId = codec.serialize((Key<?>) key);
172         return mapNode.findChildByArg(childId).map(codec::createBindingProxy);
173     }
174
175     @NonNull MapNode mapNode() {
176         return mapNode;
177     }
178
179     private @NonNull State<K, V> lookupState() {
180         final State<K, V> local;
181         return (local = (State<K, V>) STATE.getAcquire(this)) != null ? local : loadLookup();
182     }
183
184     private @NonNull State<K, V> iterState() {
185         final State<K, V> local;
186         return (local = (State<K, V>) STATE.getAcquire(this)) != null ? local : loadIter();
187     }
188
189     @SuppressWarnings("unchecked")
190     private @NonNull State<K, V> loadLookup() {
191         final State<K, V> ret = new LazyBindingMapLookupState<>(this);
192         final Object witness;
193         return (witness = STATE.compareAndExchangeRelease(this, null, ret)) == null ? ret : (State<K, V>) witness;
194     }
195
196     @SuppressWarnings("unchecked")
197     private @NonNull State<K, V> loadIter() {
198         final State<K, V> ret = new LazyBindingMapIterState<>(this);
199         final Object witness;
200         return (witness = STATE.compareAndExchangeRelease(this, null, ret)) == null ? ret : (State<K, V>) witness;
201     }
202
203     private static UnsupportedOperationException uoe() {
204         return new UnsupportedOperationException("Modification is not supported");
205     }
206
207     abstract static class State<K extends Key<V>, V extends DataObject & KeyAware<K>> {
208         abstract boolean containsKey(@NonNull Object key);
209
210         abstract V get(@NonNull Object key);
211
212         abstract @NonNull Set<K> keySet();
213
214         abstract @NonNull Collection<V> values();
215
216         abstract @NonNull Set<Entry<K, V>> entrySet();
217     }
218 }