c0f3fcb7bb4716eb275b9dd38591d6c459f8540a
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / LazyBindingList.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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import java.lang.invoke.MethodHandles;
15 import java.lang.invoke.VarHandle;
16 import java.util.AbstractList;
17 import java.util.Collection;
18 import java.util.Comparator;
19 import java.util.List;
20 import java.util.RandomAccess;
21 import java.util.function.UnaryOperator;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.yangtools.concepts.Immutable;
24 import org.opendaylight.yangtools.yang.binding.DataObject;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30  * Lazily-populated List implementation backed by NormalizedNodes. This implementation defers creating Binding objects
31  * until they are actually needed, caching them in a pre-allocated array.
32  *
33  * <p>
34  * The cost of this deferred instantiation is two-fold:
35  * <ul>
36  *   <li>each access issues a {@link VarHandle#getAcquire(Object...)} load and a class equality check</li>
37  *   <li>initial load additionally incurs a {@link VarHandle#compareAndExchangeRelease(Object...)} store</li>
38  * </ul>
39  *
40  * @param <E> the type of elements in this list
41  */
42 final class LazyBindingList<E extends DataObject> extends AbstractList<E> implements Immutable, RandomAccess {
43     private static final VarHandle OBJ_AA = MethodHandles.arrayElementVarHandle(Object[].class);
44     private static final Logger LOG = LoggerFactory.getLogger(LazyBindingList.class);
45     private static final String LAZY_CUTOFF_PROPERTY =
46             "org.opendaylight.mdsal.binding.dom.codec.impl.LazyBindingList.max-eager-elements";
47     private static final int DEFAULT_LAZY_CUTOFF = 16;
48
49     @VisibleForTesting
50     static final int LAZY_CUTOFF;
51
52     static {
53         final int value = Integer.getInteger(LAZY_CUTOFF_PROPERTY, DEFAULT_LAZY_CUTOFF);
54         if (value < 0) {
55             LOG.info("Lazy population of lists disabled");
56             LAZY_CUTOFF = Integer.MAX_VALUE;
57         } else {
58             LOG.info("Using lazy population for lists larger than {} element(s)", value);
59             LAZY_CUTOFF = value;
60         }
61     }
62
63     private final ListNodeCodecContext<E> codec;
64     private final Object[] objects;
65
66     private LazyBindingList(final ListNodeCodecContext<E> codec,
67             final Collection<? extends NormalizedNodeContainer<?, ?, ?>> entries) {
68         this.codec = requireNonNull(codec);
69         objects = entries.toArray();
70     }
71
72     static <E extends DataObject> @NonNull List<E> create(final ListNodeCodecContext<E> codec, final int size,
73             final Collection<? extends NormalizedNodeContainer<?, ?, ?>> entries) {
74         if (size == 1) {
75             // Do not bother with lazy instantiation in case of a singleton
76             return List.of(codec.createBindingProxy(entries.iterator().next()));
77         }
78         return size > LAZY_CUTOFF ? new LazyBindingList<>(codec, entries) : eagerList(codec, size, entries);
79     }
80
81     private static <E extends DataObject> @NonNull List<E> eagerList(final ListNodeCodecContext<E> codec,
82             final int size, final Collection<? extends NormalizedNodeContainer<?, ?, ?>> entries) {
83         @SuppressWarnings("unchecked")
84         final E[] objs = (E[]) new DataObject[size];
85         int offset = 0;
86         for (NormalizedNodeContainer<?, ?, ?> node : entries) {
87             objs[offset++] = codec.createBindingProxy(node);
88         }
89         verify(offset == objs.length);
90         return List.of(objs);
91     }
92
93     @Override
94     public int size() {
95         return objects.length;
96     }
97
98     @Override
99     public E get(final int index) {
100         final Object obj = OBJ_AA.getAcquire(objects, index);
101         // Check whether the object has been converted. The object is always non-null, but it can either be in DOM form
102         // (either a MapEntryNode or UnkeyedListEntryNode) or in Binding form. We know the exact class for the latter,
103         // as we are creating it via codec -- hence we can perform a direct comparison.
104         //
105         // We could do a Class.isInstance() check here, but since the implementation is not marked as final (yet) we
106         // would be at the mercy of CHA being able to prove this invariant.
107         return obj.getClass() == codec.generatedClass() ? (E) obj : load(index, (NormalizedNodeContainer<?, ?, ?>) obj);
108     }
109
110     private @NonNull E load(final int index, final NormalizedNodeContainer<?, ?, ?> node) {
111         final E ret = codec.createBindingProxy(node);
112         final Object witness;
113         return (witness = OBJ_AA.compareAndExchangeRelease(objects, index, node, ret)) == node ? ret : (E) witness;
114     }
115
116     @Override
117     @SuppressWarnings("checkstyle:parameterName")
118     public boolean remove(final Object o) {
119         throw uoe();
120     }
121
122     @Override
123     @SuppressWarnings("checkstyle:parameterName")
124     public boolean addAll(final Collection<? extends E> c) {
125         throw uoe();
126     }
127
128     @Override
129     @SuppressWarnings("checkstyle:parameterName")
130     public boolean addAll(final int index, final Collection<? extends E> c) {
131         throw uoe();
132     }
133
134     @Override
135     @SuppressWarnings("checkstyle:parameterName")
136     public boolean removeAll(final Collection<?> c) {
137         throw uoe();
138     }
139
140     @Override
141     @SuppressWarnings("checkstyle:parameterName")
142     public boolean retainAll(final Collection<?> c) {
143         throw uoe();
144     }
145
146     @Override
147     @SuppressWarnings("checkstyle:parameterName")
148     public void sort(final Comparator<? super E> c) {
149         throw uoe();
150     }
151
152     @Override
153     public void replaceAll(final UnaryOperator<E> operator) {
154         throw uoe();
155     }
156
157     @Override
158     protected void removeRange(final int fromIndex, final int toIndex) {
159         throw uoe();
160     }
161
162     private static UnsupportedOperationException uoe() {
163         return new UnsupportedOperationException("Modification not supported");
164     }
165 }