2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static java.util.Objects.requireNonNull;
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;
20 import java.util.Optional;
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;
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).
40 * @param <V> value type
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;
49 static final int LAZY_CUTOFF;
51 private static final VarHandle STATE;
55 STATE = MethodHandles.lookup().findVarHandle(LazyBindingMap.class, "state",
57 } catch (NoSuchFieldException | IllegalAccessException e) {
58 throw new ExceptionInInitializerError(e);
61 final int value = Integer.getInteger(LAZY_CUTOFF_PROPERTY, DEFAULT_LAZY_CUTOFF);
63 LOG.info("Lazy population of maps disabled");
64 LAZY_CUTOFF = Integer.MAX_VALUE;
66 LOG.info("Using lazy population for maps larger than {} element(s)", value);
71 private final @NonNull Unordered<K, V> codec;
72 private final @NonNull MapNode mapNode;
74 // Used via VarHandle above
75 @SuppressWarnings("unused")
76 private volatile State<K, V> state;
78 private LazyBindingMap(final Unordered<K, V> codec, final MapNode mapNode) {
79 this.codec = requireNonNull(codec);
80 this.mapNode = requireNonNull(mapNode);
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) {
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);
90 return size > LAZY_CUTOFF ? new LazyBindingMap<>(codec, mapNode) : eagerMap(codec, mapNode, size);
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);
100 return builder.build();
105 return mapNode.size();
109 public V remove(final Object key) {
114 @SuppressWarnings("checkstyle:parameterName")
115 public void putAll(final Map<? extends K, ? extends V> m) {
120 public void clear() {
125 public boolean containsKey(final Object key) {
126 return lookupState().containsKey(requireNonNull(key));
130 public boolean containsValue(final Object value) {
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.
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.
138 * Note we prefer throwing ClassCastException/NullPointerException when presented with null or an object which
139 * cannot possibly be contained in this map.
141 final V cast = codec.getBindingClass().cast(requireNonNull(value));
142 final V found = get(cast.key());
143 return found != null && cast.equals(found);
147 public V get(final Object key) {
148 return lookupState().get(requireNonNull(key));
152 public Set<K> keySet() {
153 return iterState().keySet();
157 public Collection<V> values() {
158 return iterState().values();
162 public Set<Entry<K, V>> entrySet() {
163 return iterState().entrySet();
166 @NonNull V createValue(final MapEntryNode node) {
167 return codec.createBindingProxy(node);
170 Optional<V> lookupValue(final @NonNull Object key) {
171 final NodeIdentifierWithPredicates childId = codec.serialize((Key<?>) key);
172 return mapNode.findChildByArg(childId).map(codec::createBindingProxy);
175 @NonNull MapNode mapNode() {
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();
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();
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;
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;
203 private static UnsupportedOperationException uoe() {
204 return new UnsupportedOperationException("Modification is not supported");
207 abstract static class State<K extends Key<V>, V extends DataObject & KeyAware<K>> {
208 abstract boolean containsKey(@NonNull Object key);
210 abstract V get(@NonNull Object key);
212 abstract @NonNull Set<K> keySet();
214 abstract @NonNull Collection<V> values();
216 abstract @NonNull Set<Entry<K, V>> entrySet();